删除对象数组中的重复项 [英] Removing duplicates in array of objects
本文介绍了删除对象数组中的重复项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
可能重复:
从javascript中删除对象数组中的重复项
var arr = [{empID:100,empName:greg},{empID:101,empName:Math},{empID:100,empName:greg}];
var sorted_arr = arr.sort(); // You can define the comparing function here.
// JS by default uses a crappy string compare.
var results = [];
for (var i = 0; i < arr.length - 1; i++) {
if (sorted_arr[i + 1].empID != sorted_arr[i].empID) {
results.push(sorted_arr[i]);
}
}
alert(results);
我有一个对象数组,但是当我尝试删除与ID匹配的重复对象时,它不会被删除。代码有什么问题。
I have an array of objects, but when i try to remove the duplicate object which matches the ID, it does not get removed. What's the issue with the code.
推荐答案
您的代码有两个问题:
- 排序不起作用
- 您忘记将最后一个元素添加到结果中
我建议采用以下替代方案:
I would suggest the following alternative:
var arr = ...;
arr.sort( function( a, b){ return a.empID - b.empID; } );
// delete all duplicates from the array
for( var i=0; i<arr.length-1; i++ ) {
if ( arr[i].empID == arr[i+1].empID ) {
delete arr[i];
}
}
// remove the "undefined entries"
arr = arr.filter( function( el ){ return (typeof el !== "undefined"); } );
这篇关于删除对象数组中的重复项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文