3

I've got a multidimensional array, like so:

let = [
 [1, 2, 3],
 [4, 5, 6],
 [7, 8, 9]
]

I need to find the index of array in which element "6" is, which in this case is index 1 as it is in second array.

Any idea how to find it? So far I've got

let theIndex = groupedButtons.map(group => {
 group.findIndex(group.forEach(e => {
  e === 6
 } ))
})

4 Answers 4

4

Here's a one liner solution using findIndex and some

let x = [
 [1, 2, 3],
 [4, 5, 6],
 [7, 8, 9]
];

const result = x.findIndex(item => item.some(number => number === 6));
console.log(result)

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

Comments

3

This will return the index you are looking for:

let matrix = [
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9]
]

function find(matrix, item) {
    return matrix.findIndex(row => row.indexOf(item) !== -1);
}

console.log(find(matrix, 6));

2D search

This will return you both row and column index

let matrix = [
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9]
]

function find2d(matrix, item) {
    let ix = 0, col = -1;
    while (ix < matrix.length && (col = matrix[ix].indexOf(item)) === -1) ix++;
    return ix === matrix.length ? undefined : [ix, col];
}

console.log(find2d(matrix, 6));

Comments

1

for one level nested array this function will work good

let arr = [
 [1, 2, 3],
 [4, 5, 6],
 [7, 8, 9]
]

function findIndex(arr,val){
    let result = null
    arr.forEach((each,i)=>{if(each.indexOf(val)>=0){result=i}})
    return result
}

console.log(findIndex(arr,6))

Comments

0

let data = [
 [1, 2, 3],
 [4, 5, 6],
 [7, 8, 9]
];

const numToFind = 6;
let index = -1;
data.forEach((x, i) => {
  if(x.some(n=>n==numToFind)){
    index = i;
  }
});

console.log(index);

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.