Skip to content Skip to sidebar Skip to footer

Comparing Two Javascript Arrays?

I want to compare two arrays with each other and see if there is a match, and if there is do something. var answers = new Array('a','b','c','d', 'e'); var correct = new Array('a','

Solution 1:

Try using this:

for(var i = 0; i < answers.length; i++) {
    for(var j = 0; j < correct.length; j++){
        if (answers[i] === correct[j]){ 
            console.log(answers[i]+ " is the correct answer")
            break;
        }
    }
}

Solution 2:

Look this post, there is a code to compare disorder arrays: http://blog.maxcnunes.net/2012/08/10/comparacao-de-arrays-desordenados-javascript/

ps: the post is in portuguese, but you can use any translater to understand

Solution 3:

Try this code:

var a = [1,2,3,4]
  , b = [1,3,5,7,9]
  , c = ['a','b','c'];

functionfindDups( arr1, arr2 ) {
  var arrs = [ arr1, arr2 ].sort(function( a,b ) {
    return a.length > b.length;
  });
  return arrs[0].filter(function( v ) {
    return ~arrs[1].indexOf( v ); 
  });
}

functionhasDups( arr1, arr2 ) {
  return !!findDups( arr1, arr2 ).length;
}

console.log( findDups( a,b ) ); //=> [1, 3]console.log( hasDups( a,c ) ); //=> false

Post a Comment for "Comparing Two Javascript Arrays?"