skip to Main Content

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


  1. The issue is with the filter() function. The map() function inside includes() returns an array, so you need to use the some() function to check if any of the customer models match the cars array.

    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) => {
      return val.customers.some((customer) => cars.includes(customer.model))
    })
    
    console.log(result)
    
    Login or Signup to reply.
  2. You can use filter with reduce with and includes:

    const cars = ['s', 'y']
    
    const inventory = [{
      desc: 'Tesla',
      customers: [{
        model: 's',
        name: 'John'
      }]
    }, {
      desc: 'Audi',
      customers: [{
        model: 'q3',
        name: 'Doe'
      }]
    }]
    
    const result = inventory.filter((item) =>
      item.customers.reduce((acc, curr) => acc || cars.includes(curr.model), false))
    
    console.log(result)
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search