I’m trying to filter the inventory
array based on the values I have in the cars
array. The result currently I’m getting is []
.
const cars = ['s', 'y']
const inventory = [{
desc: 'Tesla',
customers: [{
model: 's',
name: 'John'
}]
}, {
desc: 'Audi',
customers: [{
model: 'q3',
name: 'Doe'
}]
}]
const result = inventory.filter((val) => {
cars.includes(val.customers.map((val) => val.model))
})
console.log(result)
The result what I’m expecting is below. Could anyone please help?
[{
desc: 'Tesla',
customers: [{
model: 's',
name: 'John'
}]
}]
2
Answers
The issue is with the
filter()
function. Themap()
function insideincludes()
returns an array, so you need to use thesome()
function to check if any of the customer models match the cars array.You can use
filter
withreduce
with andincludes
: