且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

从阵列中使用JavaScript删除重复的对象

更新时间:2022-06-24 03:39:20

我明白了,这个问题存在这种复杂性是平方。还有一招去做,它通过使用关联数组简直是。

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];
}

更新以包括保罗的评论。谢谢!