Is there a way to find the index of an array within an array?

I tried this and it didn’t work. I also looked for documentation for this but couldn’t find any. Is there any way to locate the array and retrieve its index without using a loop?

let arr = [['a'], ['b']]
console.log(arr.indexOf(['a']))

You would need to create a custom function to achieve this result.

Would I still use indexOf() for this?

1 Like

The custom function you would need to write would be passed to the findIndex method.

Depending how nested the array you are looking for, this could be some complex logic.

1 Like

It is related to this:

Your original code is asking if any of the array elements are stored in the same place as the array you created for the argument of indexOf, and none of those memory addresses will match up.

I abandoned the logic from that post, I’m trying something else now xD

It is the same logical problem though. You can’t dodge the need to understand array/object references. The issue will pop up in any moderately complex work with arrays or objects.

1 Like
let x = [['a'], ['a']] // array x contains two different arrays
x.indexOf(['a']) // here goes another one array ['a'] and it doesn't equal to arrays in x

let a = ['a'] 
let b = a // a and b holds ref to the same array.
// if you change the arr through b
b[0] = 'k'
// you'll get the change through a
console.log(a[0]) // 'k'

I think I might have dodged it by using join() and comparing it that way. I’m doing the Interview Prep, I’ll post my detailed solution here. It technically does the trick but still fails 2 of the requirements simply because of how cumbersome it is I guess. It does return the correct values though.