How to Find an Array Index by Condition Using JavaScript?

Learn how to find an array index based on a condition

Starting ES6+, we can use findIndex() to get the index of the first matched array element that satisfies the provided testing function. If the value does not exist in the array, -1 is returned. For example:

// ES6+
const negativeNumber = (elem) => elem < 0;

[101, 5, -4, 202, -4].findIndex(negativeNumber); // 2

[10, 22, 44, 0, 15].findIndex(negativeNumber); // -1

There's no built-in JavaScript method to get the last matched array element that satisfies the provided testing function. To do so, we'll have to use a custom solution.


Hope you found this post useful. It was published . Please show your love and support by sharing this post.