I have an array similar to the following:
const myArray: number[][] = [[1,2,3],[4,5,6]]
I want to get the index of a specific element. With a simple 1D array, i can use [1,2,3].indexOf(1), which return 0. But it does not work for my case.
I have an array similar to the following:
const myArray: number[][] = [[1,2,3],[4,5,6]]
I want to get the index of a specific element. With a simple 1D array, i can use [1,2,3].indexOf(1), which return 0. But it does not work for my case.
You could collect all indices of the arrays for the wanted value.
const
findIndex = (array, value) => {
if (!Array.isArray(array)) return;
let i = array.indexOf(value),
temp;
if (i !== -1) return [i];
i = array.findIndex(v => temp = findIndex(v, value));
if (i !== -1) return [i, ...temp];
},
data = [[1, 2, 3], [4, 5, 6]];
console.log(findIndex(data, 1));
console.log(findIndex(data, 5));
You can't use indexOf directly like this on 2D array, as it uses strict equality and try to match the target value with element of outer which are arrays so you get -1 always.
You can use findIndex and includes like this
const myArray = [[1,2,3],[4,5,6]]
let indexFinder = (arr,target) => {
return arr.findIndex(v=> v.includes(target))
}
console.log(indexFinder(myArray,1))
console.log(indexFinder(myArray,6))