Home > Blockchain >  Looping through inner array in a filter function in JS
Looping through inner array in a filter function in JS

Time:01-26

I'm trying to filter the array here but the result seem to be empty. How do I loop through inner array in a filter function?

Below is the snippet

const carIds = ['100', '101'];
const carsList = [{
  name: 'BMW',
  id: '100'
}, {
  name: 'Jeep',
  id: '101'
}, {
  name: 'Audi',
  id: '103'
}];
const result = carsList.filter((val) => val.id === carIds.map((val) => val))
console.log('result', result)

Expected output should be

[{
  name: 'BMW',
  id: '100'
}, {
  name: 'Jeep',
  id: '101'
}]

Could anyone please advise?

CodePudding user response:

I'm not completely sure what you're trying to do with the .map() method, but you're not using it right. .map() applies a transformation function to each element of the array, then returns a new array of the result. See the MDN article for help with the correct usage.

In your case, you can just use the .includes() method to check if the array includes the value. Like this:

const carIds = ['100', '101'];
const carsList = [{
  name: 'BMW',
  id: '100'
}, {
  name: 'Jeep',
  id: '101'
}, {
  name: 'Audi',
  id: '103'
}];
const result = carsList.filter(val => carIds.includes(val.id))
console.log('result', result)

Note that in this case, it is faster to use a Set, as it can check for membership in O(1) time rather than the O(n) that an array offers. Expand the snippet below for an example:

const carIds = new Set(['100', '101']);
const carsList = [{
  name: 'BMW',
  id: '100'
}, {
  name: 'Jeep',
  id: '101'
}, {
  name: 'Audi',
  id: '103'
}];
const result = carsList.filter(val => carIds.has(val.id))
console.log('result', result)

CodePudding user response:

I'm guessing you want to return the cars who's ID's are included in the carIds array?

If so you want to use the .includes() method instead of .map().

const result = carsList.filter((val) => carIds.includes(val.id))
  • Related