JavaScript - Compare two multidimensional arrays

前端 未结 2 1659
無奈伤痛
無奈伤痛 2020-12-30 17:02

I have two multidimensional arrays:

first is something like ([\'one\',\'one\',\'three\'],[\'four\',\'five\',five\'],[\'one\',\'one\',\'one\'])

a

相关标签:
2条回答
  • 2020-12-30 17:49

    Possible duplicate of How to compare arrays in JavaScript?.

    For a strict array comparison, check their length and values like so:

    var a1 = [1, 2, 3];
    var a2 = [1, 2, 3];
    
    array_compare(a1, a2);
    
    function array_compare(a1, a2) {
     if(a1.length != a2.length) {
      return false;
     }
     for(var i in a1) {
      // Don't forget to check for arrays in our arrays.
      if(a1[i] instanceof Array && a2[i] instanceof Array) {
       if(!array_compare(a1[i], a2[i])) {
        return false;
       }
      }
      else if(a1[i] != a2[i]) {
       return false;
      }
     }
     return true;
    }
    
    0 讨论(0)
  • 2020-12-30 18:03
    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/

    0 讨论(0)
提交回复
热议问题