Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Contents

Searching arrays

Searching an array is a constant need: is the product in the cart, where in the list is a certain user, are all form fields filled in. Each of these questions has its own method, and all of them save you from writing a loop with checks by hand.

includes — yes or no

includes() answers the simplest question: is the value in the array? The result is true or false:

const colors = ['red', 'green', 'blue'];
 
console.log(colors.includes('blue')); // true

The comparison is strict, like ===: the string '5' and the number 5 are different values.

indexOf — at which position

indexOf() returns the index of the first match or -1 when the value is absent:

const colors = ['red', 'green', 'blue'];
 
console.log(colors.indexOf('green')); // 1
console.log(colors.indexOf('black')); // -1

lastIndexOf() searches the same way, but from the end of the array.

find — the first matching element

When a value has to be found by a condition, use find(). It returns the first element for which the function returned true, or undefined:

const numbers = [3, 8, 15, 4];
 
console.log(numbers.find((n) => n > 5)); // 8

Most often it is used to find an object in a list by one of its properties:

const users = [
  { id: 1, name: 'Anna' },
  { id: 2, name: 'Oleg' },
];
 
const user = users.find((u) => u.id === 2);
 
console.log(user.name); // Oleg

findIndex — the index by a condition

findIndex() works like find() but returns the index of the found element or -1. You need the index, for example, to replace or remove the element afterwards:

const numbers = [3, 8, 15, 4];
 
console.log(numbers.findIndex((n) => n > 10)); // 2

The findLast() and findLastIndex() methods search the same way, starting from the end.

some and every — checking the whole array

some() tells whether at least one element matches, and every() whether all of them do:

const ages = [17, 22, 35];
 
console.log(ages.some((age) => age < 18));  // true
console.log(ages.every((age) => age < 18)); // false
MethodReturns
includes()true or false
indexOf()an index or -1
find()an element or undefined
findIndex()an index or -1
some() / every()true or false

Common mistake

The result of indexOf() cannot be used in a condition directly. An element at index 0 gives a falsy value, and a missing one (-1) a truthy one:

const colors = ['red', 'green'];
 
if (colors.indexOf('red')) {
  console.log('Found');
} else {
  console.log('Not found'); // Not found
}

For a yes-or-no question use includes(), and compare the result of indexOf() with -1.

Thanks for reading!

Donate to the site — we work hard for you.