Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
132
rated 0 times [  134] [ 2]  / answers: 1 / hits: 92390  / 8 Years ago, thu, october 6, 2016, 12:00:00

I'm learning JS. Supposing I have the below array of objects:



var family = [
{
name: Mike,
age: 10
},
{
name: Matt
age: 13
},
{
name: Nancy,
age: 15
},
{
name: Adam,
age: 22
},
{
name: Jenny,
age: 85
},
{
name: Nancy,
age: 2
},
{
name: Carl,
age: 40
}
];


Notice that Nancy is showing up twice (changing only the age). Supposing I want to output only unique names. How do I output the above array of objects, without duplicates? ES6 answers more than welcome.



Related (couldn't find a good way for usage on objects):





EDIT Here's what I tried. It works well with strings but I can't figure how to make it work with objects:



family.reduce((a, b) => {
if (a.indexOf(b) < 0 ) {
a.push(b);
}
return a;
},[]);

More From » arrays

 Answers
5

You could use a Set in combination with Array#map and a spread operator ... in a single line.



Map returns an array with all names, which are going into the set initializer and then all values of the set are returned in an array.





var family = [{ name: Mike, age: 10 }, { name: Matt, age: 13 }, { name: Nancy, age: 15 }, { name: Adam, age: 22 }, { name: Jenny, age: 85 }, { name: Nancy, age: 2 }, { name: Carl, age: 40 }],
unique = [...new Set(family.map(a => a.name))];

console.log(unique);





For filtering and return only unique names, you can use Array#filter with Set.



var family = [{ name: Mike, age: 10 }, { name: Matt, age: 13 }, { name: Nancy, age: 15 }, { name: Adam, age: 22 }, { name: Jenny, age: 85 }, { name: Nancy, age: 2 }, { name: Carl, age: 40 }],
unique = family.filter((set => f => !set.has(f.name) && set.add(f.name))(new Set));

console.log(unique);




[#60490] Monday, October 3, 2016, 8 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
paolam

Total Points: 437
Total Questions: 107
Total Answers: 106

Location: Aland Islands
Member since Wed, Nov 17, 2021
3 Years ago
;