1

I have an array of > 1000 objects, each with a nested array that looks something like that:

data = [{
  "id": 0,
  "location": "A",
  "basket": [
    "milk",
    "bread",
    "sugar",
    "water"
  ],
}, {
  "id": 1,
  "location": "B",
  "basket": [
    "chocolate",
    "cereal",
    "sugar",
    "sauce"
  ],
}, {
  "id": 2,
  "location": "C",
  "basket": [
    "milk",
    "cereal",
    "soda",
    "flour"
  ],
}]

I have a multi-select dropdown menu that has the list of all items in the "basket" nested array. When I select "sugar", it should be able to return the objects with id=0 and id=1 or if I select both "water" and "milk" should return objects with id=0 and id=2. I have tried using a combination of _.map _.find _.filter, but it doesn't work. Also tried looking for similar questions here, but didn't find one. prefer to use lodash if possible.

3
  • Thanks! Both works beautifully! Commented Mar 20, 2019 at 21:10
  • Thanks again for the update, actually I don't need that here as I need to filter strictly for the selected items in the basket. But it's good to know. So the first solution works perfect for me. The reason why i use lodash is because i also use lodash for my other filter functions, so just to keep it consistent. Commented Mar 21, 2019 at 15:13
  • Good to hear. Side note: you can comment under an answer; that way it is clear what the comment is referring to, and the one who answered (me, in this case) will be notified of your comment. I did not notice the comment above until today :-) Commented Mar 25, 2019 at 7:54

1 Answer 1

1

You can use this:

var result = _.filter(data, { basket: ['sugar', 'milk'] });

Replace the array of products with whatever you are looking for. They must all occur in the same item for it to be retained in the result.

Although you clearly indicate you prefer a lodash-based solution, I want to add the vanilla JS way as well:

var filtered = data.filter(function(item){
    return ['sugar', 'milk'].every(product => item.basket.includes(product));
});

When you want the logic to be that only some of the selected products need to occur in the basket for it to get selected, then also in the lodash version you'll need a callback:

var result = _.filter(data, function(item) {
    return _.intersection(item.basket, ['sugar', 'milk']).length;
});

In the vanilla JS version, replace every by some.

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

Comments

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.