2

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?

1
  • map() returns an array. How can val.id be equal to an array? Commented Jan 26, 2023 at 0:43

2 Answers 2

2

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)

Sign up to request clarification or add additional context in comments.

Comments

2

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))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.