0

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.

1 Answer 1

2

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>

Sign up to request clarification or add additional context in comments.

3 Comments

This is very close to what I'm looking for. From this result, is there a way to filter through each selected property and limit it to the values from sel? So instead of getting {"id":2, "selected":[1,2,3,4,5]} i would get {"id":1, "selected":[1,2,3]}. Currently everything I'm doing is traversing and I'm seeing that lodash is a really good solution to simplifying code. Thanks!
you can map the output and filter the selected array, I added an example in the first case
I have a bit of learning to do but the answer is very clear, thanks again!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.