Home > Enterprise >  Find index in multidimensionnal array
Find index in multidimensionnal array

Time:06-22

I wish to find the postion (id) of a value in multidimensionnal array.

var arr = [
  ['France', 'FA', 'Paris'],
  ['Allemagne', 'AJ', 'Berlin']
];

var x = 'France';

var index = arr.findIndex(id => id === x);

console.log(index);

Expected : 0, Got: -1

CodePudding user response:

Since id is an array you can't directly compare it to a string. Instead use something like includes.

var arr = [
  ['France', 'FA', 'Paris'],
  ['Allemagne', 'AJ', 'Berlin']
];

var x = 'France';

var index = arr.findIndex(subarr => subarr.includes(x));

console.log(index);

If you still want a compare function you can also try out some, this is more useful if you need to check something like an object property.

var arr = [
  ['France', 'FA', 'Paris'],
  ['Allemagne', 'AJ', 'Berlin']
];

var x = 'France';

var index = arr.findIndex(subarr => subarr.some(id => id === x));

console.log(index);

CodePudding user response:

You have to make a custom search function for multi-dimensional arrays

Like the following

var arr = [
 
   ['France','FA','Paris']
  ,['Allemagne', 'AJ', 'Berlin'] 

];
var x = 'AJ';


function get2DIndex(arr, query){
  let iter = 0;
  for(let i =0; i < arr.length; i  ){
  
    for(let j = 0; j < arr[i].length; j  ){
      if(query === arr[i][j]) return iter;
      
      iter  ;
    
    }
  }
  

}

var index = get2DIndex(arr, x)

console.log(index);

CodePudding user response:

You can use Array.includes() with Array.findIndex()

const arr = [
 
   ['France','FA','Paris']
  ,['Allemagne', 'AJ', 'Berlin'] 

];

const findPosition = (list, key) => list.findIndex((item) => item.includes(key));

console.log(findPosition(arr, 'France'));

CodePudding user response:

You can use Array#reduce to find every occurrence of the string you are searching for. the results are [[row,column],....]

var arr = [
  ['France', 'FA', 'Paris'],
  ['Allemagne', 'AJ', 'Berlin']
];

var x = 'France';

let result = arr.reduce((acc,e,i) => {
    let index = e.indexOf(x)
    if(index > -1)
        acc.push([i,index])
    return acc
},[])

console.log(result)

  • Related