简体   繁体   English

如何从 javascript 中的列表中获取唯一对象列表

[英]How to get list of unique objects from list in javascript

I need a list of unique objects based on a specific key.我需要一个基于特定键的唯一对象列表。

const array = [
  {"name": "Joe", "age": 42},
  {"name": "Donald", "age": 69},
  {"name": "John", "age": 42},
]

How can i get a list of unique objects selected from the list assuming i want a list of people with unique ages.假设我想要一个具有独特年龄的人的列表,我如何获得从列表中选择的独特对象的列表。

const result = [
  {"name": "Joe", "age": 42},
  {"name": "Donald", "age": 69}
]

How can this be done in a performant way, is there a better way than iterating through the elements in a foreach and adding it if it does not exist in the resulting array?如何以高效的方式完成此操作,是否有比遍历 foreach 中的元素并在结果数组中不存在时添加它更好的方法?

One way is to feed the array to a Map where you key them by age.一种方法是将阵列提供给 Map,您可以在其中按年龄键入它们。 That will eliminate duplicates, only retaining the last in the series of duplicates.这将消除重复,只保留一系列重复中的最后一个 Then extract the values again from it:然后再次从中提取值:

 const array = [{"name": "Joe", "age": 42},{"name": "Donald", "age": 69},{"name": "John", "age": 42}]; const uniques = Array.from(new Map(array.map(o => [o.age, o])).values()); console.log(uniques);

If you want to retain the first of duplicates, then first reverse the array.如果要保留第一个重复项,则首先反转数组。

Another option is to track seen values, here using a Set passed as a closure and checking for values using its .has() method to return a boolean to a filter() call.另一种选择是跟踪seen的值,这里使用作为闭包传递的Set并使用其.has()方法检查值以将 boolean 返回到filter()调用。 This will retain the first seen objects.这将保留第一次看到的对象。

 const array = [ { "name": "Joe", "age": 42 }, { "name": "Donald", "age": 69 }, { "name": "John", "age": 42 }, ] const unique = (seen => array.filter(o =>.seen.has(o.age) && seen.add(o;age)))(new Set()). console.log(unique)

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

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