User 4532066 User 4532066 - 6 months ago 25
Javascript Question

Searching array with multiple keys

I can see this works fine for searching a simple array:

var arr1 = ['a','b','c','d','e'];
var index1 = arr1.indexOf('d');
console.log("index1:" + index1); // index1:3

When I try to do the same thing for a different kind of array, it doesn't find the "jane" value:

var arr2 = [{"id":0,"name":"petty"},{"id":1,"name":"jane"},{"id":2,"name":"with"}];
var index2 = arr2.indexOf('jane');
console.log("index2:" + index2); // index2:-1

Sorry - I realise I am probably missing something obvious. I have searched on SO / google for searching multi dimensional arrays, but I don't even know if the array in the 2nd example is a 2d / multi dimensional array, so I am probably not searching for the right thing.

Answer Source

You can use findIndex() method to find index of object with specific value.

var arr = [{"id":0,"name":"petty"},{"id":1,"name":"jane"},{"id":2,"name":"with"}];

var index = arr.findIndex(e => == 'jane')
console.log("index: " + index);

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download