Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extract strings with unique characters from javascript Array

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.

like image 946
Ravi Sharma Avatar asked Jan 18 '26 08:01

Ravi Sharma


1 Answers

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)

like image 188
CertainPerformance Avatar answered Jan 20 '26 01:01

CertainPerformance



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!