In JavaScript, searching through an array can be useful for finding specific elements, checking for the existence of elements, or performing other operations on the array.
In this article, we’ll look at some examples of when and how to use array search methods, such as indexOf(), includes(), find(), filter(), and sort().
Whether you’re looking for a specific user in a list of users, or a specific product in a list of products, these methods can help you get the job done. Let’s dive in!
indexOf()
The indexOf()
method of the Array
object returns the index of the first occurrence of the element in the array or -1
if the element is not found.
Here is an example:
const colors = ['red', 'green', 'blue'];
const index = colors.indexOf('green');
console.log(index); // Output: 1
You can also pass a second argument to the indexOf()
method to specify the index at which to start the search.
For example:
const colors = ['red', 'green', 'blue', 'green', 'orange'];
const index = colors.indexOf('green', 2);
console.log(index); // Output: 3
If you need to search for multiple elements, you can use a for
loop to iterate over the array and check each element using one of the above mentioned methods.
const colors = ['red', 'green', 'blue', 'purple', 'orange'];
const searchColors = ['green', 'blue'];
const foundColors = [];
for (const color of searchColors) {
const index = colors.indexOf(color);
if (index !== -1) {
foundColors.push(color);
console.log(`Found ${color} at index ${index}`);
}
}
console.log(foundColors); // Output: ['green', 'blue']
This code will output the following:
Found green at index 1
Found blue at index 2
includes()
The includes()
method returns a boolean value (true or false) indicating whether the element exists in the array or not.
It takes two arguments: valueToFind
and fromIndex
. valueToFind
argument is the element that you want to search for in the array. And fromIndex
argument is an optional argument that specifies the index at which to start the search.
Here’s an example of how to use the includes() method to search for an element in an array:
const colors = ['red', 'green', 'blue'];
const hasGreen = colors.includes('green');
console.log(hasGreen); // Output: true
You can also pass a second argument to the includes()
method to specify the index at which to start the search.
const colorsWithMultipleInstances = ['red', 'green', 'blue', 'green', 'orange'];
const hasGreenAfterIndexOne = colorsWithMultipleInstances.includes('green', 2);
console.log(hasGreenAfterIndexOne); // Output: true
You can also pass numerical values to the includes()
method to specify the index at which to start the search.
const numbers = [1, 2, 3, 4, 5, 3];
const hasThreeAfterIndexTwo = numbers.includes(3, 2);
console.log(hasThreeAfterIndexTwo); // Output: true
find()
To search through an array using the find() method, you can use a callback function to specify the test that each element in the array must pass to be considered a match.
array.find(callback[, thisArg])
Here’s an example of how to use the find()
method to search for an element in an array:
const colors = ['red', 'green', 'blue'];
const foundColor = colors.find(color => color === 'green');
console.log(foundColor); // Output: 'green'
You can also pass a second argument to the find()
method to specify the index at which to start the search:
const colors = ['red', 'green', 'blue', 'green', 'orange'];
const foundColor = colors.find(color => color === 'green', 2);
console.log(foundColor); // Output: 'green'
filter()
The filter()
method is used to create a new array that only contains elements from the original array that satisfy a given condition.
This method is most useful when searching for elements in an array that satisfy a specific condition, and it is often used as an alternative to the forEach()
method or the for...of
loop when you need to create a new array from the elements in an existing array.
const colors = ['red', 'green', 'blue'];
const foundColors = colors.filter(color => color === 'green' || color === 'blue');
console.log(foundColors); // Output: ['green', 'blue']
The filter()
method is different from other array search methods because it returns an array of all the elements that match the specified condition, rather than just the first matching element.
This makes it useful not only for searching for multiple elements in an array but also for creating a new array that only contains the elements that satisfy a given condition.
Below are a few specific examples of using filter()
.
Filtering an array of objects based on a property value.
const students = [
{ name: 'John', grade: 'A' },
{ name: 'Jane', grade: 'B' },
{ name: 'James', grade: 'A' },
{ name: 'Jill', grade: 'C' }
];
const honorRollStudents = students.filter(student => student.grade === 'A');
console.log(honorRollStudents);
// Output: [
// { name: 'John', grade: 'A' },
// { name: 'James', grade: 'A' }
// ]
Filtering an array of numbers based on a range of values.
const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
const evenNumbers = numbers.filter(number => number % 2 === 0);
console.log(evenNumbers); // Output: [2, 4, 6, 8, 10]
Filtering an array of strings based on a regex pattern.
const words = ['apple', 'banana', 'cherry', 'date', 'elderberry'];
const wordsWithDoubleLetters = words.filter(word => word.match(/([a-z])\1/));
console.log(wordsWithDoubleLetters); // Output: ['apple', 'cherry', 'elderberry']
sort()
The sort()
method is not typically used to search for elements in an array because it is designed to sort them in an array based on a given comparator function.
However, it is possible to use sort() by passing a callback function:
const colors = ['red', 'green', 'blue'];
const foundColor = colors.sort((a, b) => a === 'green' ? -1 : 1)[0];
console.log(foundColor); // Output: 'green'
In this example, we have an array of colors called colors
. We use sort()
to search for the element 'green'
in the array.
The sort()
method takes a comparator function as an argument, and the comparator function specifies how the elements in the array should be sorted.
In this case, the comparator function tests each element to see if it is equal to 'green'
.
If an element is equal to 'green'
, it is considered to be “less than” the other elements, so it is placed at the beginning of the array. If an element is not equal to 'green'
, it is considered to be “greater than” the other elements, so it is placed at the end.
Summary
This article covers five different ways to search through arrays in JavaScript. Here is a quick summary of what each method does / situations where it is most useful:
- The
indexOf()
method is used to search for an element in an array and return its index. - The
includes()
method is used to search for an element in an array and return a boolean value indicating whether the element was found. - The
find()
method is used to search for the first element in an array that satisfies a given condition and return the element. - The
filter()
method is used to search for multiple elements in an array that satisfy a given condition and return a new array containing those elements. - The
sort()
method is used to sort the elements in an array based on a given comparator function.