0

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.

2

4 Answers 4

1

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

Sign up to request clarification or add additional context in comments.

1 Comment

I'd like to note that findIndex was added only in ECMAScript 2015, and it is not compatible with some browsers (esp. Internet Explorer). See developer.mozilla.org/en/docs/Web/JavaScript/Reference/…
0

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' })

Comments

0

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

3 Comments

Nested iterators/generators seem pretty inefficient, as Nenad already posted. This will be better: arr.findIndex(e => e.name == 'jane')
@JonasLibbrecht, right, but only if you know the key in advance.
@ Nina Scholz, that's correct but then you are performing a needle in a haystack search and that's basically inefficient on it's own and should not be implemented like this. That issue would be better solved with binary trees or something else.
0
var arr = [{"id":0,"name":"petty"},{"id":1,"name":"jane"},{"id":2,"name":"with"}];
arr.findIndex((item)=>{return item.name=="petty"})
//output is 0

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.