mihajloWR mihajloWR - 1 year ago 153
Javascript Question

JavaScript - Compare two multidimensional arrays

I have two multidimensional arrays:

first is something like


and the second one is like this

Now, what I want is to find match first index of first array with second array, but position of at least first two indexes from boths array must match also, eg.:

first_array (['one','one','three'],['four','five',five'],['one','one','one'])

will match

second_array (['one','one','nine'],['one','one','one'],['two','two']['two','two','two']...)

and output would be eg. 'alert('Match.').

I have tried

for(i=0; i<1; i++){
if(first_array[0] == second_array) console.log('Match');
else console.log('No match');

but I constantly get 'No match' although there is a match.
P.S. in 'for' loop, my i is i<1 because I want to compare only first index of first_array with complete second_array.

Thanks in advance

Answer Source
var md1 = [['one','one','three'],['four','five','five'],['one','one','one']];

var md2 = [['one','one','nine'],['one','one','one'],['two','two'],['two','two','two']];

//Iterate through all elements in first array
for(var x = 0; x < md1.length; x++){

    //Iterate through all elements in second array    
    for(var y = 0; y < md2.length; y++){

      /*This causes us to compare all elements 
         in first array to each element in second array
        Since md1[x] stays fixed while md2[y] iterates through second array.
         We compare the first two indexes of each array in conditional
      if(md1[x][0] == md2[y][0] && md1[x][1] == md2[y][1]){
        alert("match found");
        alert("Array 1 element with index " + x + " matches Array 2 element with index " + y);

Working Example http://jsfiddle.net/2nxBb/1/

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download