Definition and Usage
The indexOf()
function for arrays returns the index of the first found (occurrence of the) specified element.
If the element is not found, it returns -1
.
This function is used to find an element's position in an array or to check if the element exists.
This function is case-sensitive when searching for strings.
Basic Example
const colors = ["red", "green", "blue"];
/*
* Note:
* Array indices start at 0.
* The first element has index 0, the second element has index 1.
*/
// Returns the index of the first found occurrence of "red" in the colors array
const red = colors.indexOf("red");
console.log(red); // Output: 0
// Returns -1 because "yellow" is not found in the colors array
const yellow = colors.indexOf("yellow");
console.log(yellow); // Output: -1
const blue = colors.indexOf("blue", 1);
// The second argument specifies the index to start the search from.
// This argument is optional; if omitted, the search starts from index 0.
// Since the argument is 1, the search starts from the second element.
// The element "blue" is found at index 2, which is the first occurrence from index 1.
console.log(blue); // Output: 2
In strings, the indexOf()
function for strings works in the same way.
Syntax
arr.indexOf(searchElement[, fromIndex])
arr
is the array to which the indexOf()
function is applied.
Parameters
searchElement |
Required. The element to search for in the array.
Case-sensitive. |
---|---|
fromIndex |
Optional. The 0 -based index at which to start the search.
|
Return Value
The function returns the index of the first found occurrence of the specified element in the array.
If the element is not found, it returns -1
.
Example with Parameters and Return Values
/*
* If the element appears multiple times in the array,
* the index of the first found occurrence is returned.
*/
const colors = ["red", "green", "green", "blue"];
// Returns the index of the first found "green" in the colors array
const green = colors.indexOf("green");
// There are two "green" elements in the colors array
// at indices 1 and 2.
// However, the function returns the index of the first found element, which is 1.
console.log(green); // Output: 1
/*
* arr.indexOf(searchElement[, fromIndex])
*
* If the optional fromIndex argument is negative,
* it counts from the end of the array.
* However, the search is still performed from left to right.
*/
const fruits = ["apple", "bannana", "orange", "mango"];
const index = fruits.indexOf("mango", -2);
console.log(index); // Output: 3
// The fromIndex value is -2.
// Counting from the end of the array, the search starts at the second-to-last element, "orange".
// However, the search is still performed from left to right.
// The element "mango" is located to the right of "orange",
// so the index 3 is returned in the fruits array.
Things to Keep in Mind
The indexOf()
function cannot be used to search for NaN
.
const arr = [1, 2, NaN, 4, 5];
console.log(arr.indexOf(NaN)); // Output: -1
The indexOf()
function is case-sensitive when searching for strings.
const colors = ["red", "green", "blue"];
const red = colors.indexOf("Red");
// Uppercase "R" is different from lowercase "r"
console.log(red); // Output: -1
Practical Examples
Here are several practical uses of the indexOf()
function.
Checking Whether an Element Exists in an Array
Although the includes()
function is commonly used to check if an array contains a specific element, the indexOf()
function is also useful for this purpose. It returns -1
if the specified element is not found.
const arr = [1, 2, 3, 4, 5];
const element = 3;
if (arr.indexOf(element) !== -1) {
console.log(`${element} exists in the array.`);
} else {
console.log(`${element} does not exist in the array.`);
}
// Output: "3 exists in the array."
Removing Duplicate Elements from an Array
The following example demonstrates how to remove duplicate elements from an array using indexOf()
together with the forEach()
loop. This code creates a new array, uniqueArr
, without duplicates.
const arr = [1, 2, 2, 3, 4, 4, 5];
const uniqueArr = [];
arr.forEach(element => {
if (uniqueArr.indexOf(element) === -1) {
uniqueArr.push(element);
}
});
console.log(uniqueArr); // Output: [1, 2, 3, 4, 5]
Code Explanation
The forEach()
function iterates over each element of the array and applies a callback function.
Code Explanation
The push()
function adds one or more elements to the end of an array.
In this code, indexOf()
is used to check if an element already exists in uniqueArr
. Only elements not already present are added. This method works well for removing duplicates in small arrays.
Note: For large arrays, using indexOf()
for each element can be inefficient. In such cases, using a Set()
is recommended because it automatically removes duplicates and provides better performance.
const arr = [1, 2, 2, 3, 4, 4, 5];
const uniqueArr = Array.from(new Set(arr));
console.log(uniqueArr); // Output: [1, 2, 3, 4, 5]
Code Explanation
The Array.from()
function converts an array-like or iterable object into a new array.
In this example, Set()
is an iterable object that automatically removes duplicate values. Converting it back to an array returns a new array without duplicates.
Checking for an Element within a Specific Range
const arr = [1, 2, 3, 4, 5];
const element = 3;
const startIndex = 1;
const endIndex = 3;
const subArray = arr.slice(startIndex, endIndex + 1);
if (subArray.indexOf(element) !== -1) {
console.log(`${element} exists within the specified range of the array.`);
} else {
console.log(`${element} does not exist within the specified range of the array.`);
}
// Output: "3 exists within the specified range of the array."
Code Explanation
The slice()
function for arrays extracts a portion of an array based on a specified index range and returns a new array.
In this example, the portion between startIndex
and endIndex
is extracted. The indexOf()
function is then used on this subarray to check whether the element exists within the specified range.
Compatibility
Method |
Desktop Chrome
|
DesktopDesktop Edge
|
Desktop Firefox
|
Safari
|
Node.js
|
---|---|---|---|---|---|
indexOf()
|
1 | 12 | 1.5 | 3 | 0.10 |
Specifications
Specification | |
---|---|
Array.prototype.indexOf()
|
ECMAScript Language Specification #sec-array.prototype.indexof |