1

I want to search an array of arrays and see if there exists an array equal to a certain array I supply. I tried to use indexOf() but that wouldn't work. Does anyone have a good technique for this?

var ary = [['1','2'],['3','4'],['5','6']];
ary.indexOf(['1','2']); //I want to get 0 here, or something like -1 if it's not present
  • You need a loop and a deep comparison. – SLaks Jun 12 '15 at 21:35
  • 1
    [First, learn how to compare two arrays](http://stackoverflow.com/questions/7837456/comparing-two-arrays-in-javascript) and then loop through your array and compare each item to the "search array" – tcigrand Jun 12 '15 at 21:37
  • what if you search for ['2','1'] is that the same as ['1','2']? – Octopus Jun 12 '15 at 21:37
  • http://stackoverflow.com/questions/6315180/javascript-search-array-of-arrays This one should help. – Quentin Jun 12 '15 at 21:38

3 Answers3

1

Use indexOf with join. It's not necessary with one dimensional arrays, but is a valid approach in this escenario:

var comp = ['1','2'];

for(var i = 0, j = ary.length;i < j;i++) {
    if(ary[i].join().indexOf(comp.join()) >= 0) {
       //do stuff here
    }
}
user2755140
  • 1,917
  • 4
  • 13
  • 16
  • `ary[i].join() === comp.join()` would make it a lot clearer what you are doing here.What you are doing can actually yield false positives. Consider `[1, [1,2]]` vs `[1,2]`. – Felix Kling Jun 12 '15 at 21:42
  • Regarding performance: is it best to compare strings or arrays? – user2755140 Jun 12 '15 at 21:43
1

var ary = [['1','2'],['3','4'],['5','6']];

function contains( array, value ){
  for ( var i = 0; i < array.length; i++ ){
    if ( array[i] === value )
      return true;
    if (   value instanceof Array
        && array[i] instanceof Array
        && value.length == array[i].length ){
      var found = true;
      for ( var j = 0; j < value.length; j++ )
        if ( value[j] !== array[i][j] )
          found = false;
      if ( found )
        return true;
    }
  }
  return false;
}

console.log( contains( ary, ['1','2'] ) );
console.log( contains( ary, [1,'2'] ) );
console.log( contains( ary, ['3','4'] ) );
MT0
  • 143,790
  • 11
  • 59
  • 117
1

As for my knowledge, JavaScript has no function to check the index of a multidimensional array. You could do that manually: you declare the two values you want to find, then loop thorugh the array and check if the first and the second element of the current subarray match your condition... ... OK, I think an example is needed, sorry for my horrible explanation!

function indexMultiDArray (myArr){
    var check = ['n1','n2'];
    var i=0;
    for (i; i < myArr.length; i++){
        if (myArr[i][0]===check[0] && myArr[i][1]===check[1]){
            alert(myArr[i][0]+' '+myArr[i][1]);
        }
    }
}

Basically, you loop through it: if the first and the second element of the current couplet match the first and the second element of the check couplet, you have it: do something with it ;)

PoPeio
  • 152
  • 11