lost9123193
lost9123193

Reputation: 11040

Filtering Object Array that has an array field Using Lodash

I have 2 data sets:

People:

[
    {id:1, selected:[1,2,3,4]},
    {id:2, selected:[1,2,3,4,5]},
    {id:3, selected:[11]},
    {id:4, selected:[1,2,5]}
]

selectedArray:

[1,2,3]

I can filter People.id by selectedArray:

_(People).indexBy('id').at(selectedArray).value();

But I'm stumped on how I would filter for a field that is not represented as a single value. eg. People[0].selected which is an array of integers.

Is it possible to only show People objects that contain at least 1 integer in the People selected field from selectedArray?

I tried this:

_.intersection(selectedArray, _.map(People, 'selected'));

I eventually want to have a People object array with a selected field which is limited to the integers of selectArray. So the result would be:

[
    {id:1, selected:[1,2,3]},
    {id:2, selected:[1,2,3]},
    {id:4, selected:[1,2]}
]

I'm currently going through a for loop to calculate this but I don't think it's a very good solution and I'm wondering if there's a more elegant approach than traversing through the entire object array.

Upvotes: 0

Views: 666

Answers (1)

maioman
maioman

Reputation: 18762

You can use Array.some inside the filter (vanilla js):

var sel = [1,2,3]

var arr = [
    {id:1, selected:[1,2,3,4]},
    {id:2, selected:[1,2,3,4,5]},
    {id:3, selected:[11]},
    {id:4, selected:[1,2,5]}
]

var res = arr.filter(x => x.selected.some(y => sel.some(z => z === y))).
map(x => {
 x.selected = x.selected.filter(y => sel.some(z => z === y));
 return x;
})

console.log(res)

or in lodash

var sel = [1,2,3]

var arr = [
     {id:1, selected:[1,2,3,4]},
     {id:2, selected:[1,2,3,4,5]},
     {id:3, selected:[11]},
     {id:4, selected:[1,2,5]}
]
var res = _.filter(arr, x => _.some(x.selected, y => _.some(sel, z => z == y)))

console.log(res)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.15.0/lodash.min.js"></script>

Upvotes: 2

Related Questions