Home > Blockchain >  Javascript filter by X values
Javascript filter by X values

Time:10-05

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

CodePudding user response:

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

CodePudding user response:

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>

  • Related