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
4
  • You need a loop and a deep comparison. Commented Jun 12, 2015 at 21:35
  • 1
    First, learn how to compare two arrays and then loop through your array and compare each item to the "search array" Commented Jun 12, 2015 at 21:37
  • what if you search for ['2','1'] is that the same as ['1','2']? Commented Jun 12, 2015 at 21:37
  • stackoverflow.com/questions/6315180/… This one should help. Commented Jun 12, 2015 at 21:38

3 Answers 3

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

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

Comments

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

2 Comments

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].
Regarding performance: is it best to compare strings or arrays?
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 ;)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.