简体   繁体   English

Javascript - 从数组中删除唯一元素

[英]Javascript - Remove Unique Elements from Array

I am wondering how one would go about removing unique elements from an array.我想知道如何从数组中删除唯一元素。 For example:例如:

var arr = [1, 2, 2, 4, 4] would return [2, 2, 4, 4] . var arr = [1, 2, 2, 4, 4]将返回[2, 2, 4, 4] Where [1, 2, 3] would return [] because all elements are unique.其中[1, 2, 3]将返回[]因为所有元素都是唯一的。

I believe I need to check each element with every other element in the array, but I'm not sure how to go about this.我相信我需要用数组中的每个其他元素检查每个元素,但我不知道如何去做。

Thanks!谢谢!

With ES6, you could use a Array#map and count the values with Array#forEach .使用 ES6,您可以使用Array#map并使用Array#forEach计算值。

Later use Array#filter and check the count.稍后使用Array#filter并检查计数。

If greater than 1 return true (include the item in the result set), otherwise return false (do not include item in the result set).如果大于1返回true (包括结果集中的项目),否则返回false (不包括结果集中的项目)。

 function getNotUnique(array) { var map = new Map(); array.forEach(a => map.set(a, (map.get(a) || 0) + 1)); return array.filter(a => map.get(a) > 1); } console.log(getNotUnique([1, 2, 2, 4, 4])); console.log(getNotUnique([1, 2, 3] ));

Below is basic and easy to understand for removing unique elements from array.以下是从数组中删除唯一元素的基本且易于理解的内容。

 function removeUnique(arr) { var newArr = []; for (var i = 0; i < arr.length; i++) { var count = 0; for (var j = 0; j < arr.length; j++) { if (arr[j] == arr[i]) { count++; } } if (count >= 2) { newArr.push(arr[i]); } } return newArr; } console.log(removeUnique([1, 2, 2, 4, 4]));

This should do it;应该这样做;

 var arr = [1, 2, 2, 4, 4], unq = arr.map((e,i,a) => a.filter(f => f === e ).length) .reduce((p,c,i) => c === 1 ? p : p.concat(arr[i]) ,[]); console.log(unq);

However on a second thought the following might be even more readable and efficient.然而,再想一想,以下内容可能更具可读性和效率。 We are in fact using one of the rare cases in which we can utilize laziness in JS through a short circuit.事实上,我们正在使用一种罕见的情况,在这种情况下,我们可以通过短路来利用 JS 中的惰性。

 var r = [1,2,2,4,4].filter((e,i,a) => a.lastIndexOf(e) != i || a.indexOf(e) != i); console.log(r);

So the a.indexOf(e) != i portion only runs for the unique elements and the last encountered non-unique element.所以a.indexOf(e) != i部分只针对唯一元素和最后遇到的非唯一元素运行。 Cool.凉爽的。

下面的代码返回所有重复的值

const getDuplicatedVals = (data) => data.filter( (x) => data.indexOf(x) != data.lastIndexOf(x))

Here is an implementation (using https://stackoverflow.com/a/5668029/4202031 )这是一个实现(使用https://stackoverflow.com/a/5668029/4202031

function removeUnique(arr) {
  var counts = {}

  for(var i = 0; i< arr.length; i++) {
      var num = arr[i]
      counts[num] = counts[num] ? counts[num]+1 : 1
  }

  var result = []
  for(var key in counts) {
    if(Object.prototype.hasOwnProperty.call(counts, key) && counts[key] > 1 {
      result.push(key)
    }
  }

  return result
}


var arr = [1, 2, 3]
var arr2 = [1, 1, 2, 2, 4, 6, 4]

console.log(removeUnique(arr)) // []
console.log(removeUnique(arr2)) // [ '1', '2', '4' ]

You could do something like this (strictly using arrays):可以做这样的事情(严格使用数组):

var arr = [1,2,3,4,4];
var temp = [];
var to_keep = [];
for(var x = 0; x < arr.length; x++){
  if(temp.indexOf(arr[x]) > -1) {
    if(to_keep.indexOf(arr[x]) == -1)
      to_keep.push(arr[x]);
  } else if(temp.indexOf(arr[x]) == -1) temp.push(arr[x]);
}

for(var y = 0; y < arr.length; y++){
  if(to_keep.indexOf(arr[y]) == -1){
    arr.splice(y,1);
    y--;
  }
}

// arr = [4,4];

Iterate through the array, use the value as an index into an object and increment for each occurrence in the original.遍历数组,使用该值作为对象的索引,并为原始中的每次出现递增。 Then iterate through the object and pull out those with totals greater than one.然后遍历对象并拉出总数大于 1 的对象。 Should work for string and numeric types.应该适用于字符串和数字类型。

function dupsOnly(a) {
    var T = {};
    for (var i = 0; i < a.length; i++) {
        if (a[i] in T)
            T[a[i]] += 1;
        else
            T[a[i]] = 1;
    }
    var D = [];
    for (var t in T) {
        if (T[t] > 1)
            D.push(t);
        while (T[t] > 1) {
            T[t] -= 1;
            D.push(t);
       }
    }
    return D;
}
var arr = [1, 2, 2, 4, 4]

var dict_with_count = {}
for (var i=0; i<arr.length; i++){
   dict_with_count[arr[i]] = 0
}

for (var i=0; i<arr.length; i++){
   dict_with_count[arr[i]] += 1
}

var new_list = [];

for (key in dict_with_count){
   if (dict_with_count[key] > 1){
       for (var j=0; j<dict_with_count[key]; j++){
          new_list.push(key)
       }
   }
}

console.log(new_list)

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

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