Home > Enterprise >  How to you filter out a map without using for loop or forEach and get it in an array?
How to you filter out a map without using for loop or forEach and get it in an array?

Time:02-04

how do you filter out a map without using for loop or forEach and get it in an array? so below I have a map carMap and an array isPresentArr and when iterating isPresentArr I should get the result

const carMap = {
'1' : {id: '1', isPresent: true},
'2' : {id: '2', isPresent: true},
'3' : {id: '3', isPresent: true},
'4' : {id: '4', isPresent: true},
'5' : {id: '5', isPresent: true},
}
const isPresentArr = ['1','5']
const result = [{id: '1', isPresent: true},{id: '5', isPresent: true}] 
const result = isPresentArr ?.filter((id) => { if (Object.keys(carMap).includes(id)) { return carMap[id] } })

I tried the above filter but am getting the result as ['1','5']

CodePudding user response:

Array.prototype.filter():

The filter() method creates a shallow copy of a portion of a given array, filtered down to just the elements from the given array that pass the test implemented by the provided function.

Array.prototype.map():

The map() method creates a new array populated with the results of calling a provided function on every element in the calling array.

Instead of filter use map:

const carMap = {
'1' : {id: '1', isPresent: true},
'2' : {id: '2', isPresent: true},
'3' : {id: '3', isPresent: true},
'4' : {id: '4', isPresent: true},
'5' : {id: '5', isPresent: true},
}
const isPresentArr = ['1','5'];

const result = isPresentArr?.map((id) => { if (Object.keys(carMap).includes(id)) { return carMap[id] } })
console.log(result);//[{id: '1', isPresent: true},{id: '5', isPresent: true}] 

CodePudding user response:

You can use flatMap to achieve this:

const carMap = {
'1' : {id: '1', isPresent: true},
'2' : {id: '2', isPresent: true},
'3' : {id: '3', isPresent: true},
'4' : {id: '4', isPresent: true},
'5' : {id: '5', isPresent: true},
};
const isPresentArr = ['1','5'];
const isPresentSet = new Set(isPresentArr);

const result = Object.values(carMap).flatMap(elm => isPresentSet.has(elm.id) ? elm : []);

console.log(result);

  • Related