Javascript删除所有出现的重复元素,留下唯一的唯一元素 [英] Javascript remove all occurrence of duplicate element, leaving the only one that is unique

查看:45
本文介绍了Javascript删除所有出现的重复元素,留下唯一的唯一元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I want to remove elements that occurr more than once and get the unique element. The array always has 3 elements. Lets say i have an array [2,3,2], then I need to get 3 which is only unique in the array(removing both 2s, because they occur more than once).

我已尝试使用以下代码,但肯定没有按预期工作.

I have tried with following code, but surely it doesnot work as expected.

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]

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

To check if a specific item is unique in the array, it just checks if the first index it's found at, matches the last index it's found at.

这篇关于Javascript删除所有出现的重复元素,留下唯一的唯一元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆