DEV Community

Michael Dayah for Ptable

Posted on

Two dimensional array search

A friend posed a quandary. What's the cleanest way of searching a two-dimensional array in JavaScript for an element and returning the index of its containing array?

That is, return 2 if asked to search the following for 8.

const haystack = [
 [1,2,3],
 [4,5,6],
 [7,8,9]
];
const search = 8;

My first attempt.

haystack.indexOf(haystack.find(arr => arr.includes(search)));
<- 2

Then, after learning of findIndex.

haystack.findIndex(arr => arr.includes(search));
<- 2

What if you need both the column and row in the 2-D array? The following duplicates part of the search, so it's not optimal.

const row = haystack.findIndex(row => row.includes(search));
const col = haystack[row].indexOf(search);

Maybe the function body inside findIndex can use indexOf instead and be tricked into storing its value while still returning true or false to keep from disrupting the outer findIndex, though at that point is it still functional programming and is it worth it over using traditional loops?

Top comments (1)

Collapse
 
jesuke profile image
Jesuke

Thanks, it works like a charm!!