简体   繁体   English

通过 object 属性从对象数组中获取唯一对象的有效方法?

[英]Efficient way to get unique objects from array of objects, by object property?

Here is my array of objects这是我的对象数组

const array = [ 
  {id: 1, data: "foo"}, 
  {id: 1, data: "bar"}, 
  {id: 2, data: "baz"} 
]

I want to remove all duplicate objects by its id and return only the array of objects that have an unique id.我想通过其 id 删除所有重复的对象,并仅返回具有唯一 id 的对象数组。

Expected result:预期结果:

[ 
  {id: 2, data: "baz"} 
]

This is what I have now: O(n^2)这就是我现在所拥有的:O(n^2)

function getUnique(array) {
    const newArray = []

    for (let obj of array) {
        if (array.filter(x => x.id === obj.id).length === 1) {
            newArray.push(obj)
        }
    }

    return newArray
}

Whats the more efficient way to achieve this?实现这一目标的更有效方法是什么?

Is it possible to get the time-complexity to O(n) or O(n log n)?是否有可能获得 O(n) 或 O(n log n) 的时间复杂度?

 const array = [{ id: 1, data: "foo" }, { id: 1, data: "bar" }, { id: 2, data: "baz" } ] let map = {}; array.forEach(x => { map[x.id] = (map[x.id] || 0) + 1 }); console.log(array.filter(x => map[x.id] === 1))

I would suggest to count the number of occurrences in your array and store them in a Map .我建议计算数组中出现的次数并将它们存储在Map中。 Next you filter all element, which count is 1接下来过滤所有元素,计数为1

function getUnique(arr) {
  const count = new Map();

  arr.forEach((element) => {
    count.set(element.id, (count.get(element.id) || 0) + 1);
  });

  return array.filter((element) => {
    return count.get(element.id) === 1;
  });
}

This has a runtime of 2(n) since you have to iterate over them twice这具有2(n)的运行时间,因为您必须对它们进行两次迭代

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM