Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

245
Views
Filtering array with multiple conditions (javascript/typescript)?

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.

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

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)

about 4 years ago · Juan Pablo Isaza Report

0

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

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!