Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

filter objects from array that have the same value at given key

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.

like image 217
sympi Avatar asked Dec 05 '25 08:12

sympi


1 Answers

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)
like image 186
Rajesh Avatar answered Dec 06 '25 21:12

Rajesh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!