Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

javascript

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 as both a and c are in same position and d is in the wrong position.

function () {
    var index = 0;
    for (index = 0; index < length; index++) {
        if (array1[index] == array2[index]) {
            count++
        } 
    }
    return count
}

I'm getting a return of 1. I think that's because they equal in length that is why I'm getting a 1. So I'm thinking that I now need to put another for loop and have that loop go through the elements individually, but not sure how to do this. I could be completely wrong in what I have put above, if so, could someone explain the process to me please.

like image 227
52876 Avatar asked Feb 17 '26 19:02

52876


2 Answers

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/

like image 107
Prasath K Avatar answered Feb 20 '26 08:02

Prasath K


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"] 
like image 42
Maksym Kozlenko Avatar answered Feb 20 '26 08:02

Maksym Kozlenko



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!