Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
176
rated 0 times [  183] [ 7]  / answers: 1 / hits: 15639  / 7 Years ago, fri, september 1, 2017, 12:00:00

Let's say we have an array that looks like this:



[
{
id: 0,
name: 'A'
},
{
id: 1,
name:'A'
},
{
id: 2,
name: 'C'
},
{
id: 3,
name: 'B'
},
{
id: 4,
name: 'B'
}
]


I want to keep only this objects that have the same value at 'name' key. So the output looks like this:



[
{
id: 0,
name: 'A'
},
{
id: 1,
name:'A'
},
{
id: 3,
name: 'B'
},
{
id: 4,
name: 'B'
}
]


I wanted to use lodash but I don't see any method for this case.


More From » filter

 Answers
43

You can try something like this:


Idea:



  • Loop over the data and create a list of names with their count.

  • Loop over data again and filter out any object that has count < 2




var data = [{ id: 0, name: 'A' }, { id: 1, name: 'A' }, { id: 2, name: 'C' }, { id: 3, name: 'B' }, { id: 4, name: 'B' }];

var countList = data.reduce(function(p, c){
p[c.name] = (p[c.name] || 0) + 1;
return p;
}, {});

var result = data.filter(function(obj){
return countList[obj.name] > 1;
});

console.log(result)




[#56606] Tuesday, August 29, 2017, 7 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
virginia

Total Points: 632
Total Questions: 95
Total Answers: 95

Location: China
Member since Mon, Aug 22, 2022
2 Years ago
;