Wednesday, March 22, 2023

Searching Arrays in JavaScript

Searching Arrays in JavaScript

If you already understand the basics of JavaScript arrays, it's time to take your skills to the next level with more advanced topics. In this series of tutorials, you'll explore intermediate-level topics for programming with arrays in JavaScript.

JavaScript arrays have a powerful toolset of methods to developers to sort, filter, and manipulate data. More often than not, however, you need to find data within an array, and while you can certainly accomplish that task with loops and iterations, JavaScript provides many methods for finding specific data within your arrays.

In this tutorial, you will learn how to search for and find data within JavaScript arrays by using the indexOf(), lastIndexOf(), find(), findLast(), includes(), some(), and every() methods.

Search Method Description
indexOf(), lastIndexOf() searches for a primitive value and returns its index
findIndexOf(), findLastIndexOf() searches for an element with a test function and returns its index
find(), findLast() searches for an element with a test function and returns the element itself
includes() tests whether the array includes a primitive value
some() tests whether the array has some element that matches a test function
every() tests whether all elements in the array match a test function

Finding an Element's Index

One of the most common things a developer needs to find is the index of a particular element. With an element's index, you can directly access, update, or remove an element. The ability to find the index of an element is a fundamental feature, and JavaScript provides several methods that searches an array and returns the index of the desired element.

The indexOf() and lastIndexOf() Methods

The first methods are the most simple: indexOf() and lastIndexOf(). These methods search for a specific value or object with an array and return the index of the first occurrence of that value or object. If the element is not found in the array, these methods return -1. These two methods work best with arrays that contain simple values (eg. strings and numbers).

Using indexOf()

The syntax for indexOf() is as follows:

1
array.indexOf(searchElement[, fromIndex]);

Here, the searchElement is the element you want to search for, and fromIndex is an optional parameter that specifies the index at which to start searching. If you do not provide fromIndex, the search begins at index 0. For example, consider the following code:

1
const fruit = ['orange', 'apple', 'grape', 'apple'];
2
3
fruit.indexOf('apple'); // output: 1

4
fruit.indexOf('mango'); // output: -1

5
fruit.indexOf('apple', 2)); // output: 3

6
fruit.indexOf('orange', 1); // output: -1

This code defines an array called fruit, and it contains four string values that name three different types of fruit (notice that apple is listed twice at indexes 1 and 3).

First we searched for the string apple. Because the fromIndex parameter is not specified, the search starts at the beginning of the array at index 0 and returns the value of 1.

Next, we searched for the value mango. This returns -1 because that string was not found.

The third call to indexOf() searches for apple yet again, but this time the search begins at the index of 2. Therefore, the result is 3 because the next occurrence of apple is at index 3.

The fourth call to indexOf() searches for orange, but the search starts at index 1. The result is -1 because orange does not occur at or after index 1.

Using lastIndexOf()

The lastIndexOf() method is similar to indexOf(), but it starts the search at the end of the array. It also has a similar syntax, as shown below:

1
array.lastIndexOf(searchElement[,fromIndex]);

Consider the following:

1
fruit.lastIndexOf('apple'); // output: 3
2
fruit.lastIndexOf('mango'); // output: -1
3
fruit.lastIndexOf('apple', 2)); // output: 1

In this code, the first line searches for apple. Since the search starts and the end of the array, the result is 3. The third line of code searches for apple again. This time, however, it starts searching at index 2 and results in the value of 1 because lastIndexOf() searches in reverse.

The indexOf() and lastIndexOf() methods are incredibly useful, but as mentioned before, they work best with simple values. The reason for this is because they search for the exact value passed as the searchElement. If you want to search for an object, or if you need to find a value that matches a certain criteria, the findIndex() and findLastIndex() methods are typically better options.

The findIndex() and findLastIndex() Methods

The findIndex() and findLastIndex() methods are similar in concept to the indexOf() and lastIndexOf() methods in that they search an array from the start and end of an array, respectively. However, instead of passing an exact value to search for, you pass a function that tests the elements in the array. Let's start with findIndex().

Using findIndex()

The findIndex() method finds the index of the first element in an array that satisfies the testing function. It iterates through each element of the array and calls the provided testing function with each element. Here is the method's syntax:

1
array.findIndex(testingFunction);

The testing function accepts the following three arguments: 

  • element: the element currently being tested (required)
  • index: the index of the element currently being tested (optional)
  • array: the array the find method was called upon (optional)

The findIndex() method returns the index of the first element for which the testing function returns true, or -1 if no such element is found. It stops iterating over the array as soon as the testing function returns true.

The following example demonstrates the findIndex() method:

1
const numbers = [10, 20, 30, 40];
2
3
function isNumberGreaterThan25(number) {
4
  return number > 25;
5
}
6
7
numbers.findIndex(isNumberGreaterThan25); // output: 2

This example creates an array of numbers: [10, 20, 30, 40]. It also defines the isNumberGreaterThan25() function that accepts a number parameter and returns true if the number is greater than 25. It then uses the findIndex() method to find the index of the first element in the array for which the isNumberGreaterThan25() function returns true. The findIndex() method passes each element of the array to isNumberGreaterThan25() and returns the index of the first element that satisfies the condition—which is 2 in this case.

Using findLastIndex()

As you might expect, the findLastIndex() method is very similar to findIndex(). Its syntax, seen below, is almost identical to findIndex(). The only difference, of course, is the name of the method:

1
array.findLastIndex(testingFunction);

The findLastIndex() method searches the array backwards, starting at the last element in the array. For example:

1
const numbers = [10, 20, 30, 40];
2
3
function isNumberGreaterThan25(number) {
4
  return number > 25;
5
}
6
7
numbers.findLastIndex(isNumberGreaterThan25); // output: 3

This code defines the same numbers array and isNumberGreaterThan25() function, but it then calls findLastIndex() to find the index of the last element in the array for which the isNumberGreaterThan25() function returns true.  In this case, the result is 3 because the first element tested is 40, at index 3, and that satisfies the condition.

Finding Elements

While finding an element's index can be useful, sometimes you need to find the element itself. Thankfully, JavaScript arrays provide the following two methods:

  • find(): returns the first element that satisfies the provided testing function.
  • findLast(): searches the array in reverse order and returns the element that satisfies the testing function. 

Their syntax:

1
array.find(testingFunction);
2
array.findLast(testingFunction);

These methods are nearly identical to the findIndex() and findLastIndex() methods, respectively. The only difference is that they return the actual value or object that satisfies the testing function, not the index of that element. For example, consider the following code:

1
const items = [
2
  { id: 1, name: 'book', price: 40, },
3
  { id: 2, name: 'laptop', price: 1000 },
4
  { id: 3, name: 'phone', price: 600 }
5
];
6
7
const book = items.find(function(item) {
8
   return item.id === 1; 
9
}); // book object

10
11
const lessThan10 = items.findLast(function(item) {
12
    return item.price < 10;
13
}); // undefined

This code defines an array of items, where each item is an object with id, name, and price properties. We use the find() and findLast() methods to search for objects that satisfy certain conditions, and store the result in variables.

In the first example, we use the find() method to find the object that has an id equal to 1. The testing function returns true if the id property of the current object is equal to 1, which stops the iteration and returns the current object. In this case, the first object in the array has an id property of 1, so the find() method returns the "book" object.

The second example uses the findLast() method to find the last object in the items array that has a price less than 10. In this case, none of the objects in the array satisfy the condition, so the findLast() method returns undefined

Testing if Elements Exist

The last set of methods do not return an index or an element. Instead, they return a boolean value that indicates if an element exists within the array.

The includes() Method

The first and most simple method is includes(). It simply accepts the value that you want to search for, as shown below:

1
array.includes(searchElement);

The includes() method returns true if the array contains the searchElement; otherwise, it returns false. The following code demonstrates this:

1
const fruit = ['apple', 'banana', 'cherry'];
2
3
fruit.includes('banana'); // true

4
fruit.includes('orange'); // false

This code creates an array of fruit, and we use the includes() method to check if the array includes a particular element or not. In the first example, we check if the array includes the string banana--the result of which is true. In the second example, we check if the array includes the string orange. It does not exist in the array; therefore, it returns false.

Like indexOf() and lastIndexOf(), the includes() method is well suited for simple values. If you need to work with more complex objects, or you need to define search criteria via a testing function, then consider using the some() method.

The some() Method

We use the some() method to check whether at least one element in the array satisfies the provided testing function. It iterates through each element of the array and calls the testing function with each element. It returns true if the testing function returns true for at least one element, otherwise false.

Its syntax is similar to the find() and other find methods, as shown here:

1
array.some(testingFunction);

Additionally, the testing function uses the same parameters and should return the same values as the find methods. For example:

1
const numbers = [10, 20, 30, 40];
2
3
function isEven(number) {
4
  return number % 2 === 0;
5
}
6
7
function isOdd(number) {
8
  return number % 2 !== 0;
9
}
10
11
numbers.some(isEven); // true

12
numbers.some(isOdd); // false

In this example, we define an array called numbers and two functions, isEven() and isOdd(), which return true if the provided number is even or odd, respectively. We then use the some() method to check if the array numbers includes at least one even or odd number.

In the first example, we pass the isEven() function as the testing function. The some() method stops iterating as soon as the isEven() function returns true, which in this code, is the first element in the array. Therefore, the some() method returns true.

In the second example, we pass the isOdd() function as the testing function. In this case, the array does not contain any odd numbers. Therefore, the some() method returns false.

The every() Method

You can use the every() method to check whether all elements in the array satisfy the provided testing function. It iterates through each element of the array and calls the testing function with each element. It returns true if the testing function returns true for all elements.

As you may have guessed, the syntax is familiar:

1
array.every(testingFunction);

Using the every() method is also reminiscent of the various methods we've discussed thus far. For example:

1
const numbers = [10, 20, 30, 40];
2
3
function isMultipleOfTen(number) {
4
  return number % 10 === 0;
5
}
6
7
numbers.every(isMultipleOfTen); // true

This code creates an array of numbers and defines a function called isMultipleOfTen(). If the number passed to isMultipleOfTen() is a multiple of 10, it returns true. Otherwise, it returns false. We then use the every() method to check if all the elements in the array are multiples of 10. In this case, all the elements in the array are multiples of 10, so the every() method returns true

Conclusion

Arrays are a powerful tool that lets developers easily work with multiple values, and they provide a wide array of useful and efficient methods that make it easy to search and find the data you need to work with in your code.

The indexOf(), lastIndexOf(), findIndex(), findLastIndex(), find(), findLast(), includes(), some(), and every() methods are all useful for searching arrays based on different criteria, such as the value of an element, the index of an element, or whether at least one or all elements satisfy a certain condition. By using these methods appropriately, you can make your code more efficient, readable, and maintainable, and enhance the functionality of your JavaScript applications.


No comments:

Post a Comment