简体   繁体   English

从javascript数组中提取具有唯一字符的字符串

[英]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:我尝试使用 Array.forEach() 方法来实现它:

 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:我会根据字符串 Set 的大小是否与字符串的长度相同来.filter

 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) (一个 Set 不会保存重复的元素,因此,例如,如果将 4 个元素放入一个 set 并且 2 个元素与其他元素重复,则 Set 的结果大小将为 2)

You can check by creating sets from strings also, a Set object will always have unique values.您也可以通过从字符串创建集合来检查,一个Set对象将始终具有唯一值。

 var a = ["abb", "abc", "abcdb", "aea", "bbb", "ego"]; console.log(a.filter(v => v.length === new Set(v).size))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM