如何从 JavaScript 数组中删除重复的对象?

2022-01-10 00:00:00 arrays duplicates unique javascript

从对象数组中删除重复对象的最佳方法是什么?

What's the best way to remove duplicate objects from array of objects?

来自

var arr = 
    [
        {"name":"Joe", "age":17}, 
        {"name":"Bob", "age":17}, 
        {"name":"Carl", "age": 35},
        {"name":"Bob", "age":35},
        {"name":"Joe", "age":17}, 
    ]

删除重复项后,预期的结果是

when duplicates removed, the expected result is

res= arr = 
    [
        {"name":"Joe", "age":17}, 
        {"name":"Bob", "age":17}, 
        {"name":"Carl", "age": 35},
        {"name":"Bob", "age":35},
    ]

(5 个对象,1 个重复,4 个左).

(5 objects, 1 duplicate, 4 left).

每个对象的属性数量是固定的,每个数组的属性名称相同.但是,从一个数组到另一个数组,它们可能不仅仅是上面的名称"和年龄",而是属性的名称可以是任何名称.

The number of properties of each object is fixed, the properties names are the same for each array. However, from array to array they may not be just "name" and "age" as above, but the names of the properties could be any.

@Pointy 请将上述问题中的重复词视为口头意义上的重复" - 对象分别具有相同数量的属性、相同的属性和相同的属性值.

@Pointy Please treat the duplicate word in the question above as 'duplicate' in the verbal sense - the object with the same number of properties, the same properties and the same values of that properties respectively.

这不是重复的 从 JavaScript 数组中删除重复项一个>

推荐答案

你可以使用一个对象来查找,如果一个对象已经被插入或者没有.

You could use an object for lookup, if an object is alreday inserted or not.

更新以获取对象的所有属性并使用键的值.如果只使用一些属性,那么我建议使用带有相关键的数组,例如

Update for getting all properties of the object and use the values for the key. If only some properties should be used for it, then I suggest to use an array with the relavant keys, like

['name', 'age']

并与它一起使用

var key = ['name', 'age'].map(function (k) { return a[k]; }).join('|');

var arr = [{ "name": "Joe", "age": 17 }, { "name": "Bob", "age": 17 }, { "name": "Carl", "age": 35 }, { "name": "Bob", "age": 35 }, { "name": "Joe", "age": 17 }],
    filtered = arr.filter(function (a) {
        var key = Object.keys(a).map(function (k) { return a[k]; }).join('|');
        if (!this[key]) {
            return this[key] = true;
        }
    }, Object.create(null));

console.log(filtered);

相关文章