Home > Back-end >  Filtering array with multiple conditions (javascript/typescript)?
Filtering array with multiple conditions (javascript/typescript)?

Time:03-10

Right now I have an array of objects

array = [
{
text: 'Example 1',
colorCode: '1'
},
{
text: 'Example 2',
colorCode: '2'
},
{
text: 'Example 3',
colorCode: '3'
}, 
text: 'Example 4',
colorCode: '3'
}
]

then I have an array of filters

filters = [1, 3]

I'm attempting to write a function that returns an array based on the filters provided so this example would return an array of objects containing example 1, example 2, and example 4.

Currently I'm creating an array and looping through the filters one at a time. Something like this

let filteredArray = [];
filters.forEach((x: number) => {  
        filteredArray = filteredArray.concat(_.filter(this.array, {colorCode: x}))
 })

However this seems redundant as I have to loop through the array for each filter, and will take more time as the array grows. I loop through the array and find all colorCode === 1, then loop through the array and find all colorCode === 3. Is there a way for me to only loop through the array one time and checking if each object.colorCode === 1 || object.colorCode === 3.

My problem with this function is that filters array are constantly changing in values and size, so the function needs to account for that rather than static values being passed.

CodePudding user response:

You can use filter to remove the items whose colorCode property is not included in the filters array..

let array=[{text:"Example 1",colorCode:"1"},{text:"Example 2",colorCode:"2"},{text:"Example 3",colorCode:"3"},{text:"Example 4",colorCode:"3"}];

const filters = [1, 3]

let result = array.filter(e => filters.includes( e.colorCode))
console.log(result)

CodePudding user response:

You can start off with the colorCode values, filter per each value, then flatten the resulting array.

const array=[{text:"Example 1",colorCode:"1"},{text:"Example 2",colorCode:"2"},{text:"Example 3",colorCode:"3"},{text:"Example 4",colorCode:"3"}];

const filters = [1, 3]

const result = [].concat( ...filters.map(f => array.filter(({colorCode:c}) =>  c === f)) );
console.log( result );

  • Related