Filtering by whether the value exists in another array
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
.