我有一个包含对象数组的对象。

obj = {};

obj.arr = new Array();

obj.arr.push({place:"here",name:"stuff"});
obj.arr.push({place:"there",name:"morestuff"});
obj.arr.push({place:"there",name:"morestuff"});

我想知道从数组中删除重复对象的最佳方法是什么。例如,obj.arr将变成。。。

{place:"here",name:"stuff"},
{place:"there",name:"morestuff"}

当前回答

我有一个完全相同的要求,即基于单个字段上的重复项删除数组中的重复对象。我在这里找到了代码:Javascript:从对象数组中删除重复项

所以在我的示例中,我要从数组中删除具有重复licenseNum字符串值的任何对象。

var arrayWithDuplicates = [
    {"type":"LICENSE", "licenseNum": "12345", state:"NV"},
    {"type":"LICENSE", "licenseNum": "A7846", state:"CA"},
    {"type":"LICENSE", "licenseNum": "12345", state:"OR"},
    {"type":"LICENSE", "licenseNum": "10849", state:"CA"},
    {"type":"LICENSE", "licenseNum": "B7037", state:"WA"},
    {"type":"LICENSE", "licenseNum": "12345", state:"NM"}
];

function removeDuplicates(originalArray, prop) {
     var newArray = [];
     var lookupObject  = {};

     for(var i in originalArray) {
        lookupObject[originalArray[i][prop]] = originalArray[i];
     }

     for(i in lookupObject) {
         newArray.push(lookupObject[i]);
     }
      return newArray;
 }

var uniqueArray = removeDuplicates(arrayWithDuplicates, "licenseNum");
console.log("uniqueArray is: " + JSON.stringify(uniqueArray));

结果:

uniqueArray是:

[{"type":"LICENSE","licenseNum":"10849","state":"CA"},
{"type":"LICENSE","licenseNum":"12345","state":"NM"},
{"type":"LICENSE","licenseNum":"A7846","state":"CA"},
{"type":"LICENSE","licenseNum":"B7037","state":"WA"}]

其他回答

您也可以使用地图:

const dedupThings = Array.from(things.thing.reduce((m, t) => m.set(t.place, t), new Map()).values());

完整样本:

const things = new Object();

things.thing = new Array();

things.thing.push({place:"here",name:"stuff"});
things.thing.push({place:"there",name:"morestuff"});
things.thing.push({place:"there",name:"morestuff"});

const dedupThings = Array.from(things.thing.reduce((m, t) => m.set(t.place, t), new Map()).values());

console.log(JSON.stringify(dedupThings, null, 4));

结果:

[
    {
        "place": "here",
        "name": "stuff"
    },
    {
        "place": "there",
        "name": "morestuff"
    }
]

简单高效的解决方案,运行时间比现有的70多个答案更好:

const ids = array.map(o => o.id)
const filtered = array.filter(({id}, index) => !ids.includes(id, index + 1))

例子:

const arr=[{id:1,名称:“one”},{id:2,名称:‘two’},{id:1,姓名:‘one’}]常量id=arr.map(o=>o.id)constfiltered=arr.filter(({id},索引)=>!ids.includes(id,索引+1))console.log(已过滤)

工作原理:

Array.filter()通过检查先前映射的id数组是否包含当前id来删除所有重复的对象({id}仅将对象销毁为其id)。为了只过滤出实际的重复项,它使用了Array.includes()的第二个参数fromIndex,索引为+1,这将忽略当前对象和所有先前对象。

由于过滤器回调方法的每一次迭代都将只搜索从当前索引+1开始的数组,这也大大减少了运行时间,因为只有以前未过滤的对象才会被检查。

这显然也适用于任何其他不称为id的键、多个键甚至所有键。

如果您不介意以后对唯一数组进行排序,这将是一个有效的解决方案:

things.thing
  .sort(((a, b) => a.place < b.place)
  .filter((current, index, array) =>
    index === 0 || current.place !== array[index - 1].place)

这样,您只需将当前元素与数组中的前一个元素进行比较。在过滤之前排序一次(O(n*log(n))比在整个数组中搜索每个数组元素的重复项(O(n²))要便宜。

str =[
{"item_id":1},
{"item_id":2},
{"item_id":2}
]

obj =[]
for (x in str){
    if(check(str[x].item_id)){
        obj.push(str[x])
    }   
}
function check(id){
    flag=0
    for (y in obj){
        if(obj[y].item_id === id){
            flag =1
        }
    }
    if(flag ==0) return true
    else return false

}
console.log(obj)

str是一个对象数组。存在具有相同值的对象(这里是一个小示例,有两个对象的item_id与2相同)。check(id)是一个函数,用于检查是否存在任何具有相同itemid的对象。如果存在,则返回false,否则返回true。根据该结果,将对象推入新的数组obj上述代码的输出为[{“item_id”:1},{“item_id”:2}]

要从对象数组中删除所有重复项,最简单的方法是使用过滤器:

var uniq={};var arr=[{“id”:“1”},{“id”:“2”};var arrFiltered=arr.filter(obj=>!uniq[obj.id]&&(uniq[obj.id]=true));console.log('arrFiltered',arrFiltered);