我需要编写一个函数来查找数组中出现多次的所有元素,然后将这些元素返回到数组中。 示例:输入:[2,7,4,10,12,27,4,7,7,12, 10] 输出:[4,7,10,12]
这是我目前所拥有的:
let arr= [4,4,6,8,8,9,10,10]
var method1 = function(a) {
var counts = [];
for(var i = 0; i <= a.length; i++) {
for(var j = i; j <= a.length; j++) {
if(i != j && a[i] == a[j]) {
counts.push(a[i]);
}
}
}
return counts;
}
console.log(method1(arr));
当数组只有两个数字时有效,但如果有更多则无效。我怎样才能独立于每个数字中有多少个重复项来计算每个数字中的一个?
感谢您的帮助!
最佳答案
你可以用哈希表来计算值,如果你有两个,就用这个元素。
var array = [2, 7, 4, 10, 12, 27, 4, 7, 7, 12, 10],
hash = Object.create(null),
result = array.filter(v => (hash[v] = (hash[v] || 0) + 1) === 2);
console.log(result);
关于javascript - 使用 for 循环在 Javascript 中创建仅包含重复项的新数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54961861/