Find index of element in array JavaScript
In this post, you will learn how to find the index of element in an array using JavaScript. There are several ways to find the index of element in array. Here, we have mentioned most of them-
JavaScript find index of element in an array using indexOf() method
The indexOf() method returns the position of the first occurrence of an element. It returns -1 if the value is not found.
Syntax-array.indexOf(item, start)
Here, item is the element that you want to find within an array, and start is the position where to start the search.
Example 1-
const fruits = ["Bus", "Truck", "Car", "Bike", "Scooty"];
let index = fruits.indexOf("Car",0);
console.log("Index of Car: "+ index);
Output of the above code:
Index of Car: 2
Example 2-
const fruits = ["Bus", "Truck", "Car", "Bike", "Scooty"];
let index = fruits.indexOf("Car",-2);
console.log("Index of car: "+ index);
Output of the above code:
Index of car: -1
JavaScript find index of element in an array using findIndex() method
The findIndex() method of JavaScript returns the index of the element that satisfies a testing function or -1 if no element passed the test.
Syntax-array.findIndex(function(currentValue, index, arr), thisValue)
Here, function is the function to execute on each element in the array until the function returns true, it takes three arguments element, index, and array and the thisValue is an optional object to be used when executing the callback.
Example 1-
In the given example, the findIndex() method finds the element index that contains an odd number.
const arr = [44, 64, 22, 89, 56, 34];
function isOdd(element, index, array) {
return (element%2 == 1);
}
console.log((arr.findIndex(isOdd)));
Example 2-
In the given example, the findIndex() method finds the element index that contains positive number.
const arr = [-44, -64, -22, 89, -56, -34];
var getPositive = arr.findIndex(function (element) {
return element > 0;
});
console.log("Index with Positive number: "+getPositive);
Output of the above code:
Index with Positive number: 3
Related Articles
Generate random numbers in JavaScriptJavascript window location
Remove duplicates from array Javascript
Scientific calculator JavaScript
How to reverse string in JavaScript
JavaScript display PDF in the browser using Ajax call
Parsing JSON in Javascript
Javascript speech recognition example
Select/deselect all checkboxes using Javascript
Print specific part of a web page in javascript
Dynamically Add/Delete HTML Table Rows Using Javascript
jQuery Ajax serialize form data example
Image popup on page load using HTML and jQuery
Ajax live data search using jQuery PHP MySQL
jQuery loop over JSON result after AJAX Success
Simple star rating system using PHP, jQuery and Ajax
jquery image zoom on mouseover example
Bootstrap star rating input example
Bootstrap datepicker example
Submit a form data without page refresh