[英]Find unique words from an array of anagrams using Map in Javascript
I know how to do it without Map
. 我知道没有
Map
可以做到这一点。 It seems more logical to use Map
for this task but I can't seem to implement it. 使用
Map
执行此任务似乎更合乎逻辑,但我似乎无法实现它。 Is this even possible? 这甚至可能吗?
So far I tied this: 到目前为止,我把它绑起来
function aclean(arr) {
let result = [];
let unique = new Map();
for(let i = 0; i < arr.length; i++){
let sorted = arr[i].toLowerCase().split("").sort().join("");
/*if (unique.add(sorted)) {
result.push(arr[i]);
}*/
}
return result;
}
let array = ["nap", "teachers", "cheaters", "PAN", "ear", "era", "hectares"];
console.log(aclean(array));
The result should be: nap,teachers,ear
or PAN,cheaters,era
结果应该是:
nap,teachers,ear
或PAN,cheaters,era
You could take a Set
with the normalized (lower case, sorted) strings and return a filtered result. 您可以使用规范化(小写,已排序)字符串获取
Set
并返回筛选结果。
function aclean(array) { let unique = new Set(); return array.filter(s => { let sorted = s.toLowerCase().split("").sort().join(""); if (!unique.has(sorted)) { unique.add(sorted); return true; } }); } let array = ["nap", "teachers", "cheaters", "PAN", "ear", "era", "hectares"]; console.log(aclean(array));
You could loop over your array using .forEach()
, and check at each iteration whether or not your Map
has a key of the sorted word, if it doesn't, then you set the sorted word as the key, and the word associated with the word as the value. 您可以使用
.forEach()
循环遍历数组,并在每次迭代时检查您的Map
是否具有已排序单词的键,如果不是,则将排序后的单词设置为键,并将相关单词设置为用这个词作为价值。 You can then return an array of your map's .values()
to get your result: 然后,您可以返回地图的
.values()
数组以获得结果:
function aclean(arr) { let unique = new Map(); arr.forEach(word => { let sorted = word.toLowerCase().split("").sort().join(""); if(!unique.has(sorted)) { unique.set(sorted, word); } }); return [...unique.values()]; } let array = ["nap", "teachers", "cheaters", "PAN", "ear", "era", "hectares"]; console.log(aclean(array));
I think Set
is prefect for this case. 我认为
Set
对于这种情况是完美的。 You can do it in following steps. 您可以按照以下步骤执行此操作。
Set
and map()
Set
和map()
创建一个唯一的排序字符串数组 map()
that array again to the value in original array which is anagram of the sorted string. map()
到原始数组中的值,该数组是已排序字符串的字谜。 const sort = str => str.toLowerCase().split('').sort().join('') const aclean = arr => [... new Set(arr.map(sort))].map(x => arr.find(a => sort(a) === x)) let array = ["nap", "teachers", "cheaters", "PAN", "ear", "era", "hectares"]; console.log(aclean(array));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.