Sudharsan S Sudharsan S - 3 months ago 9
Javascript Question

How to Compare two Arrays are Equal using Javascript?

I want position of the array is to be also same and value also same.

var array1 = [4,8,9,10];
var array2 = [4,8,9,10];


I tried like this

var array3 = array1 === array2 // returns false

Answer

You could use Array.prototype.every().(A polyfill is needed for IE < 9 and other old browsers.)

var array1 = [4,8,9,10];
var array2 = [4,8,9,10];

var is_same = (array1.length == array2.length) && array1.every(function(element, index) {
    return element === array2[index]; 
});

THE WORKING DEMO.

Comments