我正在尝试找出一种有效的方法来从数组中删除重复的对象,并寻找最有效的答案。我在互联网上搜索了一下,发现所有的方法好像都使用基本数据类型... 对于大型数组来说并不可扩展。这是我的当前实现方式,可以进行改进,我想尝试避免使用标签。
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}, ....]
顺序不重要,但如果排序可以使其更有效率,那我愿意挑战一下...
对于不了解 o 是一个标签的人,它只是表示跳回循环而不是推送到新数组。
请使用纯JavaScript,不使用库。
迄今为止的答案:
以下是性能测试的结果: http://jsperf.com/remove-duplicates-for-loops