4532066
4532066

Reputation: 2110

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.

Upvotes: 0

Views: 430

Answers (4)

Vinod kumar G
Vinod kumar G

Reputation: 655

var arr = [{"id":0,"name":"petty"},{"id":1,"name":"jane"},{"id":2,"name":"with"}];
arr.findIndex((item)=>{return item.name=="petty"})
//output is 0

Upvotes: 0

Nina Scholz
Nina Scholz

Reputation: 386578

You could check all values of the objects and use Array#findIndex instead of Array#indexOf.

var arr2 = [{ id: 0, name: "petty" }, { id: 1, name: "jane" }, { id: 2, name: "with" }],
    index2 = arr2.findIndex(o => Object.values(o).some(v => v === 'jane'));

console.log(index2);

Upvotes: 0

lukaleli
lukaleli

Reputation: 3627

First of all: it's not a multi-dimensional array. It's an array consisting of objects. It's one-dimensional. To find an object you need to iterate through an array and check the needed key, e.g.:

arr.findIndex(function(el) { return el.name === 'jane' })

Upvotes: 0

Nenad Vracar
Nenad Vracar

Reputation: 122047

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 => e.name == 'jane')
console.log("index: " + index);

Upvotes: 1

Related Questions