0

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.

1
  • what index do you want: the global, flatten index, or the index in the subarray? For example, what is the expected index for 6 in your example? Commented Jul 2, 2020 at 8:05

2 Answers 2

1

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

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

Comments

0

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

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.