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

查看:99
本文介绍了从阵列中使用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.

答案为止:

下面的答案性能测试:
<一href=\"http://jsperf.com/remove-duplicates-for-loops\">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天全站免登陆