Saturday, November 16, 2024
Google search engine
HomeLanguagesJavascriptHow to Find the Array Index with a Value in JavaScript ?

How to Find the Array Index with a Value in JavaScript ?

In this article, we will learn how to find the array index with a value in JavaScript. In JavaScript, there are multiple approaches to finding the index of an array with a specific value, including using the indexOf() method, the findIndex() method, and a for loop. Below is a list of the possible approaches:

  • Using indexOf()
  • Using findIndex()
  • Using for loop

Example 1:

Input: ['apple', 'banana', 'cherry', 'orange']
N= 'cherry'
Output: 2
The index of the word cherry is 2

Example 2:

Input: [10, 20, 30, 40]
N= 50
Output: -1
The value 50 is not present in given array. 
Hence it returns -1

 

Approach 1. Using indexOf() method

The indexOf() method in JavaScript is used to find the index of the first occurrence of a specified element in an array. It returns the index of the element if it is found in the array, otherwise, it returns -1.

Syntax: Here is the syntax for using the indexOf() method:

array.indexOf(searchElement[, fromIndex])

Parameters:

  • searchElement: It is the element you want to find the index of.
  • fromIndex: It is the optional parameter that specifies the starting index of the search. If the fromIndex parameter is omitted, the search starts from index 0. If the fromIndex parameter is negative, the search starts from the end of the array, counting backward from -1.

Here, the array indicates that specific array that you want to search for the element.

Example 1: In this example, we have an array of fruits and want to find the index of the element ‘cherry’. We use the indexOf() method to search for ‘cherry’ in the fruits array and it returns the index of ‘cherry’, which is 2.

Javascript




const fruits = ['apple', 'banana', 'cherry', 'orange'];
const index = fruits.indexOf('cherry');
console.log(index); // Output: 2


Output:

2

Example 2: In this example, we have an array of numbers and we want to find the index of the element 50. Since 50 is not present in the numbers array, the indexOf() method returns -1.

Javascript




const numbers = [10, 20, 30, 40];
const index = numbers.indexOf(50);
console.log(index); // Output: -1


Output:

-1

Approach 2. Using findIndex() method

The findIndex() method in JavaScript is used to get the index of the initial element in an array that meets a particular condition or testing function. The method returns the index of the first element that passes the test or -1 if no element passes the test. The findIndex() method does not modify the original array.

Syntax: Here is the syntax for using the findIndex() method:

array.findIndex(
    callback(currentValue[, index[, array]])[, 
    thisArg]
)

Parameters:

  • callback: The function that tests each element in the array. It requires three arguments.
  • array (optional): The array on which the findIndex() method was called.
  • currentValue: The current array element being processed.
  • index (optional): The index of the current array element to be handled.
  • thisArgument (optional): An object to which the this keyword in the callback function can refer.
    The callback function should return true if the current element passes the test; otherwise, it should return false.

Example 3: Here is an example that shows how to use the findIndex() method to find the index of the first element in an array that is greater than 25

Javascript




const array = [10, 20, 30, 40];
const index = array.findIndex(num => num > 25);
console.log(index); // Output: 2


Output:

2

In the example above, the findIndex() method applies the provided arrow function to each element of the numbers array until an element passes the test (i.e., num > 25). The function returns the index of the first element that passes the test, which is 2 in this case.

Example 4: In the example above, the findIndex() method applies the provided arrow function to each element of the fruits array, but none of the elements pass the test (i.e., fruit === ‘kiwi’). Therefore, the method returns -1.

Javascript




const fruits = ['apple', 'banana', 'cherry', 'orange'];
const index = fruits.findIndex(fruit => fruit === 'kiwi');
console.log(index); // Output: -1


Output:

-1

Approach 3. Using for loop

Another approach to finding the index of an array with a specific value is to use a for loop to iterate through the array and compare each element with the value. 

Syntax:

for (let i = 0; i < arraynumbers.length; i++) {
    if (arraynumbers[i] === value) {
        // index found, do something
        break;
    }
}

In the above syntax, an array refers to the array that needs to be searched, targetValue is the value that needs to be found, and i is the index variable used in the loop.

The loop iterates through each element of the array starting from index 0 and checks if the current element is equal to the target value. If the target value is found, the index of that element is stored in a variable, and the loop is terminated using the break statement.

Example 5: In this example, the loop iterates through each element of the numbers array and checks if the current element is equal to 30. When element 30 is found at index 2, the loop is terminated using the break statement, and index 2 is stored in the index variable. Finally, the index variable is logged to the console, which outputs 2.

Javascript




const arraynumbers = [10, 20, 30, 40];
let index = -1;
for (let i = 0; i < arraynumbers.length; i++) {
    if (arraynumbers[i] === 30) {
        index = i;
        break;
    }
}
console.log(index); // Output: 2


Output:

2

Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, neveropen Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!

RELATED ARTICLES

Most Popular

Recent Comments