Home > Web Front-end > JS Tutorial > body text

Difference between indexOf and findIndex functions

WBOY
Release: 2023-08-27 17:57:10
forward
953 people have browsed it

indexOf 和 findIndex 函数之间的区别

JavaScript is a dynamic programming language that can be used on both the client and server sides. JavaScript is used to create interactive web pages. It has many frameworks such as React JS, Angular JS, Node JS, etc. JavaScript provides some methods to get the index of a specified element. indexOf and findIndex are these methods.

indexOf function in JavaScript

The indexOf function in JavaScript allows us to search for an element in an array and returns the first found index in that array. If the element is not found, -1 is returned. The syntax of this method is as follows:

array.indexOf(element, index)
Copy after login

Here, array is the list of elements that executes the indexOf method. Element represents the element to be searched, and index is the starting position of the element to be searched.

Example

Let us consider an array of month names. We will use the indexOf method to find the index of the month "Mar"

const months = ['Jan', 'Feb', 'Mar', 'April', 'May']
console.log (months.indexOf('Mar'))
Copy after login

Output

2
Copy after login

It gives an output index of "2". If the search element does not exist in the array, "-1" is returned as output.

Console.log (months.indexOf('Aug'))
Copy after login

Since the element does not exist in the months array, the indexOf function returns "-1".

findIndex function JavaScript

The array.findIndex() function of JavaScript is used to return the index of the first element present in the array when the condition specified in the function is met. This element is passed by the user during the function call. If the element does not exist in the array, -1 is returned.

The syntax of the findIndex method is as follows:

arr.findIndex (func(element, index, arr), thisArg)
Copy after login

Here, "arr" represents the array in which the findIndex function is being executed.

The findIndex method has the following parameters:

  • func - This is the callback function for the specified condition. It takes the following parameters:

    • o element - it is the current element in the array

    • o index - Index of the current element, optional

    • o arr - Indicates that the array on which this method is executed is also optional

  • thisArg - This is an optional value

The findIndex method can be used in two ways, namely using the "return" keyword and using the "inline" function. Here, when we pass a function to another function, they are called "callback functions".

Use the "return" keyword

Suppose we have a set of colors, such as red, green, blue, yellow, orange. We want yellow indexes.

Example

const colors = ['red', 'green', 'blue', 'yellow', 'orange']

function is_yellow (element) {
   return element === 'yellow'
}
result = colors.findIndex(is_yellow)
console.log ("The index of 'yellow' is: " + result)                        

Copy after login

Output

It will produce the following output:

The index of 'yellow' is: 3
Copy after login

Here, we get the output "3" because the element "yellow" appears at index position "3".

Use inline functions

The same program mentioned above can also be written as follows:

Example

let colors = ['red', 'green', 'blue', 'yellow', 'orange']

let index = colors.findIndex(color => color === 'blue')
console.log("The index of color 'blue' is: " + index)
Copy after login

Output

It will produce the following output:

The index of color 'blue' is: 2
Copy after login

We get the output "2" because the element "blue" appears at the second position in the given array.

Difference between indexOf and findIndex functions

There are two main differences between the indexOf and findIndex methods:

First Difference

"The indexOf method takes the element as a parameter; while in the findIndex method, the callback function is passed as a parameter."

Example

The following example explains this:

const fruits = ['apple', 'banana', 'mango', 'grapes']

console.log("The index of 'banana' is: " + fruits.indexOf('banana'))
console.log ("Index: " + fruits.findIndex(index => index === 'banana'))

Copy after login

Output

It will produce the following output:

The index of 'banana' is: 1
Index: 1
Copy after login

In both cases, the output is given as "1" because the element "banana" appears at the first index. In the indexOf method, the element we want to search for is passed as parameter and the function compares each element of the array and returns the first position where the element is found.

In findIndex, this method sends each element in the array to a function that will check the array for the specified element. If the element is found, a Boolean value is returned, which is "True", and the findIndex method returns that specific index.

In both cases, if the value or element does not exist in the array, both methods return "-1" as output.

The second difference

The

indexOf method is great for getting the index of a simple element. However, this method doesn't work properly when we are looking for the index of something more complex, such as an object. This is because of "reference equality".

According to reference equality, the comparison will return true only when the two objects being compared refer to the exact same object. In JavaScript, two identical objects are not identical unless they refer to the same object.

Example

Let us understand this through the following example:

const obj = {banana:3}
const array = [{mango:7}, obj, {orange:5}]

console.log ("Index: " + array.indexOf({banana:3}))  
console.log ("Index: " + array.findIndex(index => index.banana === 3))
console.log ("Index: " + array.indexOf(obj))
Copy after login

Output

It will produce the following output:

Index: -1
Index: 1
Index: 1
Copy after login

In the first indexOf function, even though the object is the same, it cannot find it in the given array, so it returns "-1".

In the last used indexOf method, when we pass the actual reference, it returns the index of the object. The findIndex method checks all key and value pairs in the given array to find and return the correct index for that particular object.

in conclusion

The indexOf and findIndex methods both return the first index of the specified element. The indexOf method takes the element whose index is to be returned as a parameter, while the findIndex method takes a function as a parameter. But both functions return "-1" as output.

The above is the detailed content of Difference between indexOf and findIndex functions. For more information, please follow other related articles on the PHP Chinese website!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!