Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find the array index with a value?

People also ask

How do you get the index of value C from an array?

To find the index of specified element in given Array in C programming, iterate over the elements of array, and during each iteration check if this element is equal to the element we are searching for.

How do you find the index of an element?

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.

What is an array index value?

Indexing is an operation that pulls out a select set of values from an array. The index of a value in an array is that value's location within the array. There is a difference between the value and where the value is stored in an array.


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.


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


Use jQuery's function jQuery.inArray

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

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);

Use indexOf

imageList.indexOf(200)

how about indexOf ?

alert(imageList.indexOf(200));