Compare 2 array's elements against each other and return count JavaScript

后端 未结 3 660
花落未央
花落未央 2021-01-14 17:45

I have 2 arrays that I need to compare against each other and return the count of the same.

Example: compare array1 [abcd] against array2 [adce]. Return would be 2,1

相关标签:
3条回答
  • 2021-01-14 18:07

    If I interpret correctly, you want to find a count of elements that are at the same, exact position and a count of elements that are present in both arrays but not at the same position.

    var array1 = ['a', 'b', 'c', 'd'];
    var array2 = ['a', 'd', 'c', 'e'];
    var largerArray = (array1.length > array2.length)? array1 : array2;
    var shorterArray = (largerArray == array1)? array2 : array1;
    var count = {
                 exactPosition: 0, //elements at the exact position 
                 wrongPosition: 0 /*elements present in both arrays but at the wrong position*/
                };
    //loop the larger array
    for(var i = 0; i < largerArray.length; i ++) {
        if(array1[i] == array2[i]) {
            count.exactPosition ++;
        }
        //find elements at the wrong position in `largerArray`
        else if(largerArray.indexOf(shorterArray[i]) != -1) {
            count.wrongPosition ++;
        }
    }
    
    alert(count.exactPosition);
    alert(count.wrongPosition);
    

    This isn't a rock-solid approach and would not work for duplicates.

    Array.indexOf

    Fiddle: Fiddle

    0 讨论(0)
  • 2021-01-14 18:10

    You get 1 as output because length is not defined in your code

    var array1 = ['a','b','c','d'];
    var array2 = ['a','d','c','e'];
    
    var length = Math.min(array1.length,array2.length);
    var countMatched = 0,countNotMatched = 0;
    
    for(var index=0;index<length;index++)
    {
      if(array1[index] == array2[index])
        countMatched++;
      else if(array2.indexOf(array1[index]) >= 0)
        countNotMatched++;
    }
    alert(countMatched );
    alert(countNotMatched);
    

    Demo Fiddle : http://jsfiddle.net/tCKE7/2/

    0 讨论(0)
  • 2021-01-14 18:22

    There is a JS library UnderscoreJS which provides a number of useful method for processing JavaScript arrays. You can use its difference method:

    _.difference(['a','b','c','d'], ['a','d','c','e']) // returns ["b"] 
    
    0 讨论(0)
提交回复
热议问题