JavaScript

How to use find and findIndex (JS ES6)

July 5, 2021

How to use find and findIndex (JS ES6)

JavaScript in its ES6 version brought two methods to make life easier for those who need to search for elements in an array, they are: find() and findIndex()

How to use find and findIndex cover

Using find()

The find method will return the first value that matches what we are looking for, that is, whatever is passed as a parameter to the method.

This parameter must be a function that will be iterated element by the element of the target array.

If nothing is found, find will return undefined.

It is also important to mention that find does not change the value or order of the array in which it is used, it remains the same.

Now let’s see how to use find() in practice:

const nomes = ['Maria', 'Pedro', 'João', 'Alberto'];

console.log(nomes.find((nome) => nome == 'Pedro')); // 'Pedro'

function numeroPar(num) {
    if(num % 2 === 0) {
        return num;
    }
}

const numeros = [1,3,5,6,9,12];
console.log(numeros.find(numeroPar)); // 6
const numeros2 = [1,3,5,7,9];
console.log(numeros2.find(numeroPar)); // undefined

Notice that in the first example we used an arrow function, which also works with both methods.

Using findIndex()

In the case of findIndex() instead of returning the element, it will return the index of the first element that satisfies the condition we set in the argument passed.

If no element matches what we are looking for, the method will return -1.

Like find(), findIndex() does not change the order or value of array elements.

Now let’s see how to apply findIndex():

const itens = ['Pera', 'Maçã', 'Banana', 'Melão'];

console.log(itens.findIndex((item) => item == 'Banana')); // 2

const idades = [12,15,13,14,22];

function maiorDeIdade(idade) {
    if(idade >= 18) {
        return idade;
    }
}

console.log(idades.findIndex(maiorDeIdade)); // 4
const idades2 = [12,15,13,14,10];
console.log(idades2.findIndex(maiorDeIdade)); // -1

Conclusion

We saw that find() will return the element that satisfies the condition of the function we impose on the method, and findIndex() returns the element’s index instead of its value.

Neither method modifies the order or value of array elements

And they are a great feature to help us search for something in arrays, we can pass conditions and functions as arguments to make our search even more specific.

Also check out our Youtube channel with a lot of content about programming, by clicking here.

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x