H.org
  • Questions

Filtering by whether the value exists in another array

  1. javascript
  2. lodash

There may be times when you need to filter an array based on values defined elsewhere. Like finding a bunch of items based on their presence in another array.

Luckily, lodash has some methods that will help us with this and it's a relatively simple process.


const shoppingList = [
'milk',
'eggs',
'cheese',
'chocolate'
];

const priceList = [
{ name: 'milk', price: 1 },
{ name: 'eggs', price: 1.5 },
{ name: 'cheese', price: 2.75 },
{ name: 'beer', price: 3.99 },
{ name: 'bread', price: 0.9 }
];

const prices = _.filter(priceList, (v) => _.includes(shoppingList, v.name));

The prices array will contain:

[
{
name: 'milk',
price: 1
},
{
name: 'eggs',
price: 1.5
},
{
name: 'cheese',
price: 2.75
},
]

So, lets break this down to work out what it's doing.

The filter function in lodash allows you to select items from an array using a predicate function. This predicate function returns a boolean indicating that the item matches some expression. If it returns true then the item is selected, false and it's skipped.

By supplying the predicate function with a call to includes, we are checking if the item in the shoppingList is present in the priceList.

Ko-Fi button Support Me on Ko-fi

Created with lots of green tea and 11ty

Opinions are solely my own and not those of my employer.

Privacy Policy - Licenses