Categories
JavaScript Answers

How to get the index of the object inside an array, matching a condition with JavaScript?

Spread the love

To get the index of the object inside an array, matching a condition with JavaScript, we use the findIndex method.

For instance, we write

const a = [
  { prop1: "abc", prop2: "foo" },
  { prop1: "def", prop2: "bar" },
  { prop1: "ghi", prop2: "baz" },
];

const index = a.findIndex((x) => x.prop2 === "bar");
console.log(index);

to call findIndex with a callback that checks if the prop2 property of any object in a equals to 'bar'.

If the callback returns true, then the first index of the object with the condition true is returned.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published.