I want to extract only those strings which have unique characters, I have an array of strings:
var arr = ["abb", "abc", "abcdb", "aea", "bbb", "ego"];
Output: ["abc", "ego"]
I tried to achieve it using Array.forEach() method:
var arr = ["abb", "abc", "abcdb", "aea", "bbb", "ego"];
const filterUnique = (arr) => {
var result = [];
arr.forEach(element => {
for (let i = 0; i <= element.length; i++) {
var a = element[i];
if (element.indexOf(a, i + 1) > -1) {
return false;
}
}
result.push(element);
});
return result;
}
console.log(filterUnique(arr));
Want to know is any other way to achieve this task ?
Any suggestion.
I'd .filter by whether the size of a Set of the string is the same as the length of the string:
const filterUnique = arr => arr
.filter(str => new Set(str).size === str.length);
console.log(filterUnique(["abb", "abc", "abcdb", "aea", "bbb", "ego"]));
(a Set will not hold duplicate elements, so, eg, if 4 elements are put into a set and 2 are duplicates of others, the resulting size of the Set will be 2)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With