Javascript删除所有重复元素,只留下唯一的一个

时间:2014-10-21 11:28:39

标签: javascript arrays

我想删除多次出现的元素并获取唯一元素。该数组总是有3个元素。 假设我有一个数组[2,3,2],那么我需要得到3,这在数组中是唯一的(删除两个,因为它们不止一次出现)。

我尝试使用以下代码,但肯定无法按预期工作。

var firstArrTemp = [2,3,2];
var sorted_arr = firstArrTemp.sort();
var unique_element;
for (var i = 0; i < sorted_arr.length - 1; i++) {
    if (sorted_arr[i + 1] != sorted_arr[i]) {
        unique_element=sorted_arr[i];
    }
}

alert(unique_element);

谢谢!

5 个答案:

答案 0 :(得分:6)

这应该可以解决问题:

Array.prototype.getUnique = function(){
    var uniques = [];
    for(var i = 0, l = this.length; i < l; ++i){
        if(this.lastIndexOf(this[i]) == this.indexOf(this[i])) {
            uniques.push(this[i]);
        }
    }
    return uniques;
}

// Usage:

var a = [2, 6, 7856, 24, 6, 24];
alert(JSON.stringify(a.getUnique()));

console.log(a.getUnique()); // [2, 7856]

要检查某个特定项是否在数组中是唯一的,它只检查它所找到的第一个索引是否匹配它找到的最后一个索引。

答案 1 :(得分:3)

使用filter()函数的一种替代方法:

var myArray = [1,2,3,2,2,4,3,7,3].sort();
var uniqueValues = myArray.filter(function(item, i, arr) {
  return (item !== arr[i-1] && item !== arr[i+1]);
});

uniqueValues = [1,4,7]

答案 2 :(得分:1)

替代方案:

var a = [2,3,2], result = [];

for(var i = 0; i < a.length; i++){

    if(getAllIndexes(a, a[i]).length === 1)
        result.push(a[i]);
}

console.log(result);

function getAllIndexes(arr, val) {
    var indexes = [], i = -1;
    while (~(i = arr.indexOf(val, i+1)))
        indexes.push(i);
    return indexes;
}

答案 3 :(得分:1)

到目前为止,其他所有答案的时间复杂度都为O(n log n)或更差。尽管可以使用集合(O(n)具有Set.has的复杂性)而不是嵌套循环,但这可以在O(1)时间内完成:

// .sort has complexity O(n log n): it's not needed here, avoid it
const getOnlyUniques = (arr) => {
  const foundOnce = new Set();
  const foundTwice = new Set();
  arr.forEach((item) => {
    if (foundOnce.has(item)) {
      foundTwice.add(item);
    }
    foundOnce.add(item);
  });
  return arr.filter(item => !foundTwice.has(item));
};
console.log(getOnlyUniques([2, 3, 2]));

答案 4 :(得分:0)

当要从数组中删除重复项时,我通常使用一种方法:

const arrWithDuplicates = [1,2,2,2,3,4,4]
const arrWithUniqueValues = [...new Set(arrWithDuplicates)]

// result will be: [1,2,3,4]

这也适用于字符串和布尔值。