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

230
Views
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 answers
Answer question

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 Report

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 Report

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