获取JavaScript数组中的所有唯一值(删除重复项)

本文探讨了多种JavaScript数组去重的实现方式,包括原型方法、jQuery、Underscore.js及ES6的Set和filter方法。文章对比分析了不同方法的优缺点,提供了代码示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

本文翻译自:Get all unique values in a JavaScript array (remove duplicates)

I have an array of numbers that I need to make sure are unique. 我需要确定一个唯一的数字数组。 I found the code snippet below on the internet and it works great until the array has a zero in it. 我在互联网上找到了下面的代码片段,并且在数组中包含零之前,它都可以正常工作。 I found this other script here on SO that looks almost exactly like it, but it doesn't fail. 我在SO上找到了另一个脚本 ,看起来几乎完全一样,但是它不会失败。

So for the sake of helping me learn, can someone help me determine where the prototype script is going wrong? 因此,为了帮助我学习,有人可以帮助我确定原型脚本出了什么问题吗?

Array.prototype.getUnique = function() {
 var o = {}, a = [], i, e;
 for (i = 0; e = this[i]; i++) {o[e] = 1};
 for (e in o) {a.push (e)};
 return a;
}

More answers from duplicate question: 来自重复问题的更多答案:

Similar question: 类似的问题:


#1楼

参考:https://stackoom.com/question/8E0X/获取JavaScript数组中的所有唯一值-删除重复项


#2楼

You can also use underscore.js . 您还可以使用underscore.js

 console.log(_.uniq([1, 2, 1, 3, 1, 4])); 
 <script src="http://underscorejs.org/underscore-min.js"></script> 

which will return: 它将返回:

[1, 2, 3, 4]

#3楼

I have since found a nice method that uses jQuery 从那以后,我发现了一个使用jQuery的不错的方法

arr = $.grep(arr, function(v, k){
    return $.inArray(v ,arr) === k;
});

Note: This code was pulled from Paul Irish's duck punching post - I forgot to give credit :P 注意:此代码是从Paul Irish的鸭打孔帖子中提取 -我忘了给您以谢意了:P


#4楼

This prototype getUnique is not totally correct, because if i have a Array like: ["1",1,2,3,4,1,"foo"] it will return ["1","2","3","4"] and "1" is string and 1 is a integer; 此原型getUnique并不完全正确,因为如果我有一个类似Array的数组: ["1",1,2,3,4,1,"foo"]它将返回["1","2","3","4"]"1"是字符串, 1是整数; they are different. 它们不一样。

Here is a correct solution: 这是一个正确的解决方案:

Array.prototype.unique = function(a){
    return function(){ return this.filter(a) }
}(function(a,b,c){ return c.indexOf(a,b+1) < 0 });

using: 使用:

var foo;
foo = ["1",1,2,3,4,1,"foo"];
foo.unique();

The above will produce ["1",2,3,4,1,"foo"] . 上面将产生["1",2,3,4,1,"foo"]


#5楼

From Shamasis Bhattacharya 's blog (O(2n) time complexity) : 来自Shamasis Bhattacharya的博客 (O(2n)时间复杂度):

Array.prototype.unique = function() {
    var o = {}, i, l = this.length, r = [];
    for(i=0; i<l;i+=1) o[this[i]] = this[i];
    for(i in o) r.push(o[i]);
    return r;
};

From Paul Irish 's blog : improvement on JQuery .unique() : 来自Paul Irish的博客 :JQuery .unique()改进:

(function($){

    var _old = $.unique;

    $.unique = function(arr){

        // do the default behavior only if we got an array of elements
        if (!!arr[0].nodeType){
            return _old.apply(this,arguments);
        } else {
            // reduce the array to contain no dupes via grep/inArray
            return $.grep(arr,function(v,k){
                return $.inArray(v,arr) === k;
            });
        }
    };
})(jQuery);

// in use..
var arr = ['first',7,true,2,7,true,'last','last'];
$.unique(arr); // ["first", 7, true, 2, "last"]

var arr = [1,2,3,4,5,4,3,2,1];
$.unique(arr); // [1, 2, 3, 4, 5]

#6楼

With JavaScript 1.6 / ECMAScript 5 you can use the native filter method of an Array in the following way to get an array with unique values: 使用JavaScript 1.6 / ECMAScript 5,您可以通过以下方式使用Array的本机filter方法来获取具有唯一值的数组:

function onlyUnique(value, index, self) { 
    return self.indexOf(value) === index;
}

// usage example:
var a = ['a', 1, 'a', 2, '1'];
var unique = a.filter( onlyUnique ); // returns ['a', 1, 2, '1']

The native method filter will loop through the array and leave only those entries that pass the given callback function onlyUnique . 本地方法filter将遍历数组,仅保留那些通过给定回调函数onlyUnique

onlyUnique checks, if the given value is the first occurring. onlyUnique检查给定值是否是第一个出现。 If not, it must be a duplicate and will not be copied. 如果不是,它必须是重复的,并且不会被复制。

This solution works without any extra library like jQuery or prototype.js. 此解决方案无需任何额外的库(如jQuery或prototype.js)即可工作。

It works for arrays with mixed value types too. 它也适用于具有混合值类型的数组。

For old Browsers (<ie9), that do not support the native methods filter and indexOf you can find work arounds in the MDN documentation for filter and indexOf . 对于旧的浏览器(<IE9),不支持原生的方法filterindexOf你可以找到MDN文档中的变通过滤器的indexOf

If you want to keep the last occurrence of a value, simple replace indexOf by lastIndexOf . 如果要保留最后一次出现的值,只需将indexOf替换为lastIndexOf

With ES6 it could be shorten to this: 使用ES6可以简化为:

// usage example:
var myArray = ['a', 1, 'a', 2, '1'];
var unique = myArray.filter((v, i, a) => a.indexOf(v) === i); 

// unique is ['a', 1, 2, '1']

Thanks to Camilo Martin for hint in comment. 感谢Camilo Martin的评论提示。

ES6 has a native object Set to store unique values. ES6有一个本机对象Set用于存储唯一值。 To get an array with unique values you could do now this: 要获得具有唯一值的数组,您现在可以执行以下操作:

var myArray = ['a', 1, 'a', 2, '1'];

let unique = [...new Set(myArray)]; 

// unique is ['a', 1, 2, '1']

The constructor of Set takes an iterable object, like Array, and the spread operator ... transform the set back into an Array. Set的构造函数采用一个可迭代的对象(例如Array),并且散布运算符...将集合转换回Array。 Thanks to Lukas Liese for hint in comment. 感谢Lukas Liese的评论提示。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值