简体   繁体   English

在数组中查找单个出现的元素

[英]Find single occurrence of an element in an array

I'm trying to find single occurrence of an element in an array.我正在尝试在数组中找到单个出现的元素。 But it only shows for 1 element.但它只显示 1 个元素。 Where is the logic going wrong?逻辑错在哪里?

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])

You can use a double Array.filter() to remove numbers that appear more than once:您可以使用双Array.filter()删除出现多次的数字:

 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]

Bear in mind that this will only work for Numbers and other primitives because of the way that Javascript evaluates equality and sameness .请记住,由于Javascript 评估相等性和相同的方式,这仅适用于 Numbers 和其他原语

I added some console.logs to see what was happening and the problem is that you're changing the order of elements in arrayCopy .我添加了一些console.logs来查看发生了什么,问题是您正在更改arrayCopy中元素的arrayCopy And so 6 is never checked.所以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 ]

You can probably use a frequency map to find the number of occurrences in each element and then filter keys that occur only once.您可能可以使用频率图来查找每个元素中出现的次数,然后过滤仅出现一次的键。

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);
}

This could be done by creating an object that could map element and its occurrence.这可以通过创建一个可以映射元素及其出现的对象来完成。 So here is a code所以这是一个代码

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));
}

The output of findSingle([1, 3, 3, 6]) will be findSingle([1, 3, 3, 6])将是

[1, 6]

Note This can work with string too but it may be numbers.注意这也可以用于字符串,但它可能是数字。 For example, ["1", "3", "3", "6"]例如, ["1", "3", "3", "6"]

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

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