[javascript] How to find the array index with a value?

Say I've got this

imageList = [100,200,300,400,500];

Which gives me

[0]100 [1]200 etc.

Is there any way in JavaScript to return the index with the value?

I.e. I want the index for 200, I get returned 1.

This question is related to javascript arrays indexof

The answer is


When the lists aren't extremely long, this is the best way I know:

function getIndex(val) {
    for (var i = 0; i < imageList.length; i++) {
        if (imageList[i] === val) {
            return i;
        }
    }
}

var imageList = [100, 200, 300, 400, 500];
var index = getIndex(200);

Here is an another way find value index in complex array in javascript. Hope help somebody indeed. Let us assume we have a JavaScript array as following,

var studentsArray =
     [
    {
    "rollnumber": 1,
    "name": "dj",
    "subject": "physics"
   },
   {
   "rollnumber": 2,
  "name": "tanmay",
  "subject": "biology"
   },
  {
   "rollnumber": 3,
   "name": "amit",
   "subject": "chemistry"
   },
  ];

Now if we have a requirement to select a particular object in the array. Let us assume that we want to find index of student with name Tanmay.

We can do that by iterating through the array and comparing value at the given key.

function functiontofindIndexByKeyValue(arraytosearch, key, valuetosearch) {

    for (var i = 0; i < arraytosearch.length; i++) {

    if (arraytosearch[i][key] == valuetosearch) {
    return i;
    }
    }
    return null;
    }

You can use the function to find index of a particular element as below,

var index = functiontofindIndexByKeyValue(studentsArray, "name", "tanmay");
alert(index);

how about indexOf ?

alert(imageList.indexOf(200));

It is possible to use a ES6 function Array.prototype.findIndex.

MDN says:

The findIndex() method returns the index of the first element in the array that satisfies the provided testing function. Otherwise -1 is returned.

var fooArray = [5, 10, 15, 20, 25];
console.log(fooArray.findIndex(num=> { return num > 5; }));

// expected output: 1

Find an index by object property.

To find an index by object property:

yourArray.findIndex(obj => obj['propertyName'] === yourValue)

For example, there is a such array:

let someArray = [
    { property: 'OutDate' },
    { property: 'BeginDate'},
    { property: 'CarNumber' },
    { property: 'FirstName'}
];

Then, code to find an index of necessary property looks like that:

let carIndex = someArray.findIndex( filterCarObj=> 
    filterCarObj['property'] === 'CarNumber');

Here is my take on it, seems like most peoples solutions don't check if the item exists and it removes random values if it does not exist.

First check if the element exists by looking for it's index. If it does exist, remove it by its index using the splice method

elementPosition = array.indexOf(value);

if(elementPosition != -1) {
  array.splice(elementPosition, 1);
}

Use indexOf

imageList.indexOf(200)

Array.indexOf doesnt work in some versions of internet explorer - there are lots of alternative ways of doing it though ... see this question / answer : How do I check if an array includes an object in JavaScript?


In a multidimensional array.


Reference array:

var array = [
    { ID: '100', },
    { ID: '200', },
    { ID: '300', },
    { ID: '400', },
    { ID: '500', }
];

Using filter and indexOf:

var in_array = array.filter(function(item) { 
    return item.ID == '200' // look for the item where ID is equal to value
});
var index = array.indexOf(in_array[0]);

Looping through each item in the array using indexOf:

for (var i = 0; i < array.length; i++) {
    var item= array[i];
    if (item.ID == '200') { 
        var index = array.indexOf(item);
    }
}

// Instead Of 
var index = arr.indexOf(200)

// Use 
var index = arr.includes(200);

Please Note: Includes function is a simple instance method on the array and helps to easily find if an item is in the array(including NaN unlike indexOf)


For objects array use map with indexOf:

_x000D_
_x000D_
var imageList = [_x000D_
   {value: 100},_x000D_
   {value: 200},_x000D_
   {value: 300},_x000D_
   {value: 400},_x000D_
   {value: 500}_x000D_
];_x000D_
_x000D_
var index = imageList.map(function (img) { return img.value; }).indexOf(200);_x000D_
_x000D_
console.log(index);
_x000D_
_x000D_
_x000D_


In modern browsers you can use findIndex:

_x000D_
_x000D_
var imageList = [_x000D_
   {value: 100},_x000D_
   {value: 200},_x000D_
   {value: 300},_x000D_
   {value: 400},_x000D_
   {value: 500}_x000D_
];_x000D_
_x000D_
var index = imageList.findIndex(img => img.value === 200);_x000D_
_x000D_
console.log(index);
_x000D_
_x000D_
_x000D_

Its part of ES6 and supported by Chrome, FF, Safari and Edge


Use jQuery's function jQuery.inArray

jQuery.inArray( value, array [, fromIndex ] )
(or) $.inArray( value, array [, fromIndex ] )

Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to arrays

PHP array value passes to next row Use NSInteger as array index How do I show a message in the foreach loop? Objects are not valid as a React child. If you meant to render a collection of children, use an array instead Iterating over arrays in Python 3 Best way to "push" into C# array Sort Array of object by object field in Angular 6 Checking for duplicate strings in JavaScript array what does numpy ndarray shape do? How to round a numpy array?

Examples related to indexof

Uncaught TypeError: .indexOf is not a function indexOf and lastIndexOf in PHP? Finding second occurrence of a substring in a string in Java Index of element in NumPy array Getting Index of an item in an arraylist; In an array of objects, fastest way to find the index of an object whose attributes match a search Get value of a string after last slash in JavaScript How to find the array index with a value? Where is Java's Array indexOf? How to trim a file extension from a String in JavaScript?