var a = [[1,0],[0,1],[0,0]];
If I want to find the index position of [0,0]
? How can that be done in JavaScript?
I checked a few places and indexOf function but it doesn't work with multidimensional arrays.
var a = [[1,0],[0,1],[0,0]];
If I want to find the index position of [0,0]
? How can that be done in JavaScript?
I checked a few places and indexOf function but it doesn't work with multidimensional arrays.
You can make a hashmap of the indices and access that
var a = [[1,0],[0,1],[0,0]],
b = a.reduce((a,c,i)=>{
a[c] = i;
return a;
},{});
console.log('Index of [0,0] is ' +b[ [0,0] ] )
You could use Array#some
for outer iteration and Array#every
for inner iteration and check the length and the items.
var array = [[1, 0], [0, 1], [0, 0]],
find = [0, 0],
index = -1;
array.some(function (a, i) {
if (a.length === find.length && a.every(function (b, j) { return b === find[j]; })) {
index = i;
return true;
}
});
console.log(index);
Fast(in terms of performance) solution using while
loop and Array.prototype.every()
function:
var a = [[1,0],[0,1],[0,0]], len = a.length,
search_item = [0,1], pos = -1;
while (len--) {
if ((a[len].length === search_item.length)
&& a[len].every(function(el, i){ return el == search_item[i]; })) {
pos = len;
break;
}
}
console.log(pos);