How to find the array index with a value?
Use jQuery's function jQuery.inArray
jQuery.inArray( value, array [, fromIndex ] )
(or) $.inArray( value, array [, fromIndex ] )
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