Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Find all index based on condition

How can I get all the index based on a condition for array of objects.
I have tried below code, 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);

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

The findIndex method returns the index of the first element in the
array that satisfies the provided testing function. Otherwise, it
returns -1, indicating that no element passed the test. – MDN

You can use reduce here:

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

const result = a.reduce((acc, curr, i) => {
  if (curr.prop2 === "yutu") acc.push(i);
  return acc;
}, []);

console.log(result);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading