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

232
Visualizações
Find all index based on condition

How can I get all the indexes based on a condition for an array of objects? I have tried the code below, but it's returning only the first occurrence.

a = [
  {prop1:"abc",prop2:"yutu"},
  {prop1:"bnmb",prop2:"yutu"},
  {prop1:"zxvz",prop2:"qwrq"}];
    
index = a.findIndex(x => x.prop2 ==="yutu");

console.log(index);

over 4 years ago · Santiago Trujillo
3 Respostas
Responde à pergunta

0

findIndex will return only one matching index, You can check value against property prop2 using filter

a = [
  {prop1:"abc",prop2:"yutu"},
  {prop1:"bnmb",prop2:"yutu"},
  {prop1:"zxvz",prop2:"qwrq"}];
    
const allIndexes = a
  .map((e, i) => e.prop2 === 'yutu' ? i : -1)
  .filter(index => index !== -1);
  
  console.log(allIndexes);
  // This is one liner solution might not work in older IE ('flatMap')
 const  notSupportedInIE =a.flatMap((e, i) => e.prop2 === 'yutu' ? i : []);
 console.log(notSupportedInIE);

over 4 years ago · Santiago Trujillo Relatório

0

Try Array.reduce

a = [
  {prop1:"abc",prop2:"yutu"},
  {prop1:"bnmb",prop2:"yutu"},
  {prop1:"zxvz",prop2:"qwrq"}];
    
index = a.reduce((acc, {prop2}, index) => prop2 ==="yutu" ? [...acc, index] : acc, []);

console.log(index);

over 4 years ago · Santiago Trujillo Relatório

0

You can use normal for loop and when ever the prop2 matches push the index in the array

const a = [{
    prop1: "abc",
    prop2: "yutu"
  },
  {
    prop1: "bnmb",
    prop2: "yutu"
  },
  {
    prop1: "zxvz",
    prop2: "qwrq"
  }
];

const indArr = [];
for (let i = 0; i < a.length; i++) {
  if (a[i].prop2 === 'yutu') {
    indArr.push(i)
  }

}
console.log(indArr);

over 4 years ago · Santiago Trujillo 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