Javascript
JavaScript Fundamentals -- Arrays in JavaScript

Array.find and Array.findIndex

PRO
Outline

The find and findIndex methods on arrays are very similar. They both allow you to look through an array to find the first item that matches a given condition. find returns the whole item to you, where findIndex returns the index where the item is located in the array. If multiple items match the condition, it just returns the first item it finds. If you want all the items that match the condition, use the filter method that we talked about before. Here's how to use the find and findIndex methods:

const names = ['Preston', 'Amanda', 'Joe', 'Brooke' ];

const name = names.find(name => name.includes('a'));
console.log(name); // Amanda

const nameIndex = names.find(name => name.includes('a'));
console.log(nameIndex); // 1

If your condition doesn't match any items in the array, find will return undefined and findIndex will return -1.

 

I finished! On to the next chapter