Javascript 删除对象数组中的重复项

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13743859/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 12:47:27  来源:igfitidea点击:

Removing duplicates in array of objects

javascript

提问by theJava

Possible Duplicate:
Remove duplicates from an array of objects in javascript

可能的重复:
从 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);

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.

我有一个对象数组,但是当我尝试删除与 ID 匹配的重复对象时,它不会被删除。代码有什么问题。

回答by Sirko

Your code has two problems:

您的代码有两个问题:

  1. the sorting does not really work
  2. you forget to add the last element to the result
  1. 排序并没有真正起作用
  2. 您忘记将最后一个元素添加到结果中

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"); } );

回答by Tim Down

Provided that empIDis guaranteed to be a string or number, I would skip the sorting step and use an object as a hash of IDs that have already been seen:

如果empID保证是字符串或数字,我将跳过排序步骤并使用一个对象作为已经看到的 ID 的散列:

var arr = [
    {empID:100,empName:"greg"},
    {empID:101,empName:Math},
    {empID:100,empName:"greg"}
];

var results = [];
var idsSeen = {}, idSeenValue = {};
for (var i = 0, len = arr.length, id; i < len; ++i) {
    id = arr[i].empID;
    if (idsSeen[id] !== idSeenValue) {
        results.push(arr[i]);
        idsSeen[id] = idSeenValue;
    }
}

回答by Aesthete

Your sortfunction should really use a comparator, if you're going to be comparing items n and n+1

sort如果您要比较项目,您的函数应该真正使用比较器n and n+1

var sorted_arr = arr.sort(function(a,b) { return a.empID - b.empID; } );

This way you can be assured that sequential items in the list can possibly have duplicate empIDproperties.

通过这种方式,您可以确保列表中的连续项目可能具有重复的empID属性。