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

Javascript remove all occurrence of duplicate element, leaving the only one that is unique

本文关键字:唯一 元素 删除 Javascript      更新时间:2023-09-26

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

我尝试过使用以下代码,但肯定不会像预期的那样工作。

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

谢谢!

这应该可以做到:

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]

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

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

到目前为止,其他答案都具有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]));

替代方案:

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;
}
const nums = [1,2,3,3,3,5,5,5];
const chars = ['a','b','a','b','a','a'];
const mixed = [1,3,'b',3,'b','a','b',3];
const unique = [1,'a',3]; 
const distinct = (arr) => arr.filter((el) => arr.filter((item) => item === el).length === 1);
console.log(distinct(nums)); // [ 1, 2 ]
console.log(distinct(chars)); // []
console.log(distinct(mixed)); // [ 1, 'a' ]
console.log(distinct(unique)); // [ 1, 'a', 3 ]
  1. 首先,我们将在";arr";用";过滤器"

arr.filter((el)=>arr.filter((项)=>…);

  1. 如果";项目";等于";el";然后返回其"0";长度"

arr.filter((el)=>arr.filter((项)=>item====el).长度

  • 这将返回数组中每个元素的出现次数
  • 让我们用第一个例子来说明这一点:
  • [1,2,3,3,5,5]->[1,1,3,3,3,3.3,3]
  • 1发生1次
  • 2发生1次
  • 3发生3次
  • 5发生3次
  1. 要返回任何不重复或唯一的元素,我们只需要指定长度等于"0";1〃

arr.filter((el)=>arr.filter((项)=>item====el).length====1)

  • 这种方法允许您从要返回的元素中选择出现的次数
  • 例如,如果您想返回一个数组中出现3次的元素,则设置";长度";等于3

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

const arrWithDuplicates = [1,2,2,2,3,4,4]
const arrWithUniqueValues = [...new Set(arrWithDuplicates)]
// result will be: [1,2,3,4]

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

另一种方法,如果以前看到过键,则使用Map并将值设置为false。然后通过获取映射的值来过滤数组。

var array = [2, 3, 2],
    result = array.filter(
        Map.prototype.get,
        array.reduce((m, v) => m.set(v, !m.has(v)), new Map)
    );
console.log(result); // [3]

只有一行

arr.filter((item, pos, a) => a.lastIndexOf(item) === a.indexOf(item));

const arr = [1, 2, 3, 4, 1, 5, 6, 5];
const unique = arr.filter((item, pos, a) => a.lastIndexOf(item) === a.indexOf(item));
console.log(unique);

Util函数

Array.prototype.unique = function() {
    return this.filter((item, pos, a) => a.lastIndexOf(item) === a.indexOf(item));
}
console.log([1, 2, 3, 4, 1, 5, 6, 5].unique());

我用下面的技巧做了神奇的

if(A.length > 1 && A.length < 100000) {
    const unique_element = [];
    A.map((elem, index, arr) => {
        for(let i = 0; i < arr.length; i++)
        {
            if(arr.lastIndexOf(elem) === arr.indexOf(elem)) {
                unique_element.push(elem);
            }
        }
    })
    if(unique_element.length > 0) {
        alert(unique_element[0]);
    }
    else {
        alert("No unique value");
    }
}
else {
    process.exit(1);
}
const getUnique = (nums) => {
  let res = 0;
  nums.forEach((element) => {
    res = res ^ element;
  });
  return res;
};
console.log(getUnique([1, 3, 1, 3, 4])); // returns 4