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

86
Views
Javascript filter by X values

I have a simple javascript array of objects.

const obj = [ { id:1, color:'red' }, { id:2, color:'black' }, { id:3, color:'purple' }, { id:4, color:'grey' }, { id:5, color:'white' } ]

Let's say i have an array : colors = ['red','black'].

I want to filter obj but not like this way => obj.filter(o=>o.color==='black' || o.color==='red').

It depends on how much color in the colors array...

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

0

Use Array.includes along with Array.filter

const obj = [ { id:1, color:'red' }, { id:2, color:'black' }, { id:3, color:'purple' }, { id:4, color:'grey' }, { id:5, color:'white' } ];
const colors = ['red','black'];
const output = obj.filter(node => colors.includes(node.color));
console.log(output);

about 4 years ago · Juan Pablo Isaza Report

0

You can use a mix of filter() with findIndex():

const obj = [ { id:1, color:'red' }, { id:2, color:'black' }, { id:3, color:'purple' }, { id:4, color:'grey' }, { id:5, color:'white' } ];

const colors = ['red','black'];


let ans = obj.filter(x => colors.indexOf(x.color) > -1);

console.log(ans);

let ans2 = obj.filter(x => colors.includes(x.color));

console.log(ans2);

about 4 years ago · Juan Pablo Isaza Report

0

This one can handle multiple criterias.

const obj = [ { id:1, color:'red' }, { id:2, color:'black' }, { id:3, color:'purple' }, { id:4, color:'grey' }, { id:5, color:'white' } ]

document.getElementById("filter").addEventListener("click",function(){
  var terms=document.getElementById("term").value.split(' ');
  var filtered =[];
  obj.forEach(function(v){
    terms.forEach(function(t){
      if(v.color.includes(t)){
        filtered.push(v);
        return false;
      };
    });
  });
  
  console.log(filtered);
});
<input type='text' id='term'><button id='filter'>Filter</button>

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!