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)
You can check by creating sets from strings also, a Set
object will always have unique values.
var a = ["abb", "abc", "abcdb", "aea", "bbb", "ego"]; console.log(a.filter(v => v.length === new Set(v).size))
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.