我正在尝试查找数组中元素的单次出现。但这仅显示1个元素。逻辑错在哪里?
function findSingle(array){
var arrayCopy = array.slice(0);
var x;
var y = [];
for (var i = 0; i < array.length; i++) {
x = arrayCopy.splice(i, 1)
if(arrayCopy.includes(array[i]) === false){
console.log(array[i] + " is single")
}
arrayCopy = arrayCopy.concat(x)
}
}
findSingle([1, 3, 3, 6])
答案 0 :(得分:4)
您可以使用双https://github.com/mabbashm110/Sprint-Challenge--Responsive-Less来删除出现多次的数字:
function findSingle(arr) {
return arr.filter(i => arr.filter(j => i === j).length === 1)
}
const result = findSingle([1, 3, 3, 6, 8, 4, 6])
console.log(result) // [1, 8, 4]
请记住,由于Array.filter(),这仅适用于数字和其他primitives。
答案 1 :(得分:2)
我添加了一些console.logs
以查看发生了什么,问题是您正在更改arrayCopy
中元素的顺序。因此,6
永远不会被选中。
Checking for [ 1 ]
arrayCopy is [ 3, 3, 6 ]
1 is single
After adding to arrayCopy [ 3, 3, 6, 1 ]
Checking for [ 3 ]
arrayCopy is [ 3, 6, 1 ]
After adding to arrayCopy [ 3, 6, 1, 3 ]
Checking for [ 1 ]
arrayCopy is [ 3, 6, 3 ]
After adding to arrayCopy [ 3, 6, 3, 1 ]
Checking for [ 1 ]
arrayCopy is [ 3, 6, 3 ]
After adding to arrayCopy [ 3, 6, 3, 1 ]
您可能可以使用频率图来查找每个元素中的出现次数,然后过滤仅出现一次的键。
function findSingle(array){
var freqs = {};
array.forEach(n => {
if (!(n in freqs)) freqs[n] = 1;
else freqs[n] += 1;
});
return Object.keys(freqs).filter(k => freqs[k] === 1);
}
答案 2 :(得分:1)
这可以通过创建一个可以映射元素及其出现的对象来完成。 这是一个代码
function findSingle(arr){
var counts = {};
var singles = [];
for (var i = 0; i < arr.length; i++) {
var num = arr[i];
counts[num] = counts[num] ? counts[num] + 1 : 1;
}
for(var num in counts) {
if(counts[num] == 1)
singles.push(num);
}
return singles.map(x => Number(x));
}
findSingle([1, 3, 3, 6])
的输出将为
[1, 6]
注意,它也可以用于字符串,但可以是数字。例如,["1", "3", "3", "6"]