get the location of an item in an array
How to Get the Location of an Item in an Array
If you are working with arrays in JavaScript, you may need to find the location of a specific item within the array. Fortunately, this can be done easily using built-in array methods.
Method 1: indexOf()
The indexOf()
method returns the first index at which a given element can be found in the array, or -1 if it is not present. Here is an example:
let fruits = ['apple', 'banana', 'orange', 'pear'];
let index = fruits.indexOf('banana');
console.log(index); // output: 1
In this example, the indexOf()
method is used to get the index of the string 'banana' within the fruits
array. The returned value is 1, which is the index position of 'banana' within the array.
Method 2: findIndex()
The findIndex()
method returns the index of the first element in the array that satisfies the provided testing function. If no elements pass the test, it returns -1. Here is an example:
let numbers = [10, 20, 30, 40];
let index = numbers.findIndex(function(element) {
return element > 25;
});
console.log(index); // output: 2
In this example, the findIndex()
method is used to find the index of the first number in the numbers
array that is greater than 25. The returned value is 2, which is the index position of the number 30 within the array.
Method 3: forEach() and a conditional statement
You can also use a forEach()
loop to iterate through the array and check each element against a condition using an if
statement. Here is an example:
let animals = ['dog', 'cat', 'elephant', 'giraffe'];
let index = -1; // initialize index to -1
animals.forEach(function(element, i) {
if (element === 'elephant') { // check if element is 'elephant'
index = i; // set index to current array position
}
});
console.log(index); // output: 2
In this example, the forEach()
loop is used to iterate through the animals
array and check each element against the string 'elephant'. When the loop reaches the 'elephant' element, it sets the index
variable to the current array position. The returned value is 2, which is the index position of 'elephant' within the array.
Method 4: for loop and a conditional statement
You can also use a standard for
loop to iterate through the array and check each element against a condition using an if
statement. Here is an example:
let colors = ['red', 'green', 'blue', 'yellow'];
let index = -1; // initialize index to -1
for (let i = 0; i < colors.length; i++) {
if (colors[i] === 'green') { // check if element is 'green'
index = i; // set index to current array position
}
}
console.log(index); // output: 1
In this example, a for
loop is used to iterate through the colors
array and check each element against the string 'green'. When the loop reaches the 'green' element, it sets the index
variable to the current array position. The returned value is 1, which is the index position of 'green' within the array.