Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

88
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda