Full Stack LAMP - MEAN Developer, Python developer. Certified Azure Developer. Freelance programmer/consultant/trainer.

JavaScript – find And findIndex

The Array.prototype.findIndex() and Array.prototype.find() methods are useful to search the provided array.

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.

const ages = [20, 30, 40, 50, 60];

console.log(ages.findIndex(age => age >= 20)) 
// expected output: 0

console.log(ages.findIndex(age => age === 40)) 
// expected output: 2

console.log(ages.findIndex(age => age >= 100)) 
// expected output: -1

The find() method returns the value of the first element in the provided array that satisfies the provided testing function.

const ages = [20, 30, 40, 50, 60];

console.log(ages.find(age => age >= 20)) 
// expected output: 20

console.log(ages.find(age => age === 40)) 
// expected output: 40

console.log(ages.find(age => age >= 100)) 
// expected output: undefined

I hope you like this Post, Please feel free to comment below, your suggestion and problems if you face - we are here to solve your problems.

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments