Home > Software design >  How to find index in nested JS array
How to find index in nested JS array

Time:09-28

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

CodePudding user response:

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)

CodePudding user response:

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

CodePudding user response:

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

CodePudding user response:

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

  • Related