使用javascript从数组中删除重复的对象 [英] Remove duplicate objects from an array using javascript

查看:31
本文介绍了使用javascript从数组中删除重复的对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图找出一种有效的方法来从数组中删除重复的对象并寻找最有效的答案.我环顾互联网,似乎一切都在使用原始数据……或者对于大型阵列来说不可扩展.这是我目前的实现,可以改进并希望尽量避免使用标签.

I am trying to figure out an efficient way to remove objects that are duplicates from an array and looking for the most efficient answer. I looked around the internet everything seems to be using primitive data... or not scalable for large arrays. This is my current implementation which is can be improved and want to try to avoid labels.

 Test.prototype.unique = function (arr, artist, title, cb) {
        console.log(arr.length);
        var n, y, x, i, r;
        r = [];      
        o: for (i = 0, n = arr.length; i < n; i++) {

          for (x = 0, y = r.length; x < y; x++) {

                if (r[x].artist == arr[i].artist && r[x].title == arr[i].title) {
                    continue o;
                }
            }
            r.push(arr[i]);
        }

        cb(r);
    };

数组看起来像这样:

[{title: sky, artist: jon}, {title: rain, artist: Paul}, ....]

顺序无关紧要,但如果排序可以提高效率,那么我准备迎接挑战......

Order does not matter, but if sorting makes it more efficient then I am up for the challenge...

对于不知道 o 是一个标签的人,它只是说跳回循环而不是推送到新数组.

and for people who do not know o is a label and it is just saying jump back to the loop instead of pushing to the new array.

纯 javascript 请不要库.

Pure javascript please no libs.

目前的答案:

以下答案的性能测试:http://jsperf.com/remove-duplicates-for-loops

推荐答案

我明白了,问题在于复杂性是平方的.有一个技巧可以做到,只需使用关联数组"即可.

I see, the problem there is that the complexity is squared. There is one trick to do it, it's simply by using "Associative arrays".

您可以获取数组,对其进行循环,然后将数组的值作为键添加到关联数组中.由于它不允许重复键,您将自动删除重复项.

You can get the array, loop over it, and add the value of the array as a key to the associative array. Since it doesn't allow duplicated keys, you will automatically get rid of the duplicates.

由于您在比较时正在寻找标题和艺术家,您实际上可以尝试使用以下内容:

Since you are looking for title and artist when comparing, you can actually try to use something like:

var arrResult = {};
for (i = 0, n = arr.length; i < n; i++) {
    var item = arr[i];
    arrResult[ item.title + " - " + item.artist ] = item;
}

然后您只需再次循环 arrResult,并重新创建数组.

Then you just loop the arrResult again, and recreate the array.

var i = 0;
var nonDuplicatedArray = [];    
for(var item in arrResult) {
    nonDuplicatedArray[i++] = arrResult[item];
}

更新以包含保罗的评论.谢谢!

这篇关于使用javascript从数组中删除重复的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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