How to find the array index with a value?
Asked Answered
D

12

243

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.

Delfinadelfine answered 8/9, 2011 at 10:47 Comment(2)
Excellent answer here -> #237604Armrest
developer.mozilla.org/en/JavaScript/Reference/Global_Objects/…Coaly
L
370

You can use indexOf:

var imageList = [100,200,300,400,500];
var index = imageList.indexOf(200); // 1

You will get -1 if it cannot find a value in the array.

Lujan answered 8/9, 2011 at 10:49 Comment(6)
you can use developer.mozilla.org/en/JavaScript/Reference/Global_Objects/… or any Javascript framework to fix that.Lujan
Have just found it won't work in IE8. What's my alternative?Delfinadelfine
@Lujan How do I add this to my JS?Delfinadelfine
I've done it, thanks. IE will one day catch up with modern times!Delfinadelfine
Also won't work in recent IE if in compatibility modeBulahbulawayo
var arrayPosition = $.inArray( value, Array ); will work in all versions of IEAmbush
E
103

For objects array use map with indexOf:

var imageList = [
   {value: 100},
   {value: 200},
   {value: 300},
   {value: 400},
   {value: 500}
];

var index = imageList.map(function (img) { return img.value; }).indexOf(200);

console.log(index);

In modern browsers you can use findIndex:

var imageList = [
   {value: 100},
   {value: 200},
   {value: 300},
   {value: 400},
   {value: 500}
];

var index = imageList.findIndex(img => img.value === 200);

console.log(index);

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

Electrical answered 17/5, 2016 at 10:57 Comment(2)
Note that findIndex is not implemented in IE 11Evidentiary
@Evidentiary it is written in the answer see "Its part of ES6 and supported by Chrome, FF, Safari and (Unfortunately only) IE edge"Disconcert
R
18

Use jQuery's function jQuery.inArray

jQuery.inArray( value, array [, fromIndex ] )
(or) $.inArray( value, array [, fromIndex ] )
Renault answered 10/3, 2013 at 4:20 Comment(2)
Was going to use the code marked as the correct answer but it seems that that code wont work in all versions of IE. This answer works in all versions of IE but I changed the code slightly: var arrayPosition = $.inArray( value, Array ); works perfectlyAmbush
jQuery ≠ JavascriptDitter
B
17

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);
Benniebenning answered 12/8, 2015 at 12:51 Comment(0)
H
10

Use indexOf

imageList.indexOf(200)
Hebraist answered 8/9, 2011 at 10:50 Comment(0)
U
8

how about indexOf ?

alert(imageList.indexOf(200));
Unciform answered 8/9, 2011 at 10:51 Comment(0)
A
7

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?

Armrest answered 8/9, 2011 at 10:55 Comment(2)
according to this page developer.mozilla.org/en-US/docs/JavaScript/Reference/… you need Internet Explorer 9 for this feature (I almost wrongly assumed we were just talking IE 6 here)Renault
@Renault on that page you linked there is a polyfill for all browsers using JavaScript 1.6 and upArmrest
V
6

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);
Vanscoy answered 21/3, 2015 at 7:59 Comment(0)
O
6

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');
Overhaul answered 27/12, 2017 at 7:2 Comment(0)
T
4

In a multidimensional array.


Reference array:

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

Using filter and indexOf:

var index = array.indexOf(array.filter(function(item) { return item.ID == '200' })[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);
    }
}
Torp answered 17/2, 2020 at 19:29 Comment(0)
E
0

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);
}
Evaginate answered 24/9, 2018 at 17:35 Comment(0)
S
-1
// 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)

Seemly answered 10/4, 2018 at 10:18 Comment(2)
In addition to this only telling you if it exists, instead of getting the index/item, be cognizant of the compatibility (i.e. no IE): caniuse.com/#search=includesContemplation
includes returns a Boolean indicating if the array contains the value specified.Yeargain

© 2022 - 2024 — McMap. All rights reserved.