我试图找到一个元素在数组中的单个出现。但这仅显示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])

最佳答案

我添加了一些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);
}

10-07 21:17