How to Compare two Arrays are Equal using Javascript? [duplicate]

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

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.


A less robust approach, but it works.

a = [2, 4, 5].toString();
b = [2, 4, 5].toString();

console.log(a===b);

var array3 = array1 === array2

That will compare whether array1 and array2 are the same array object in memory, which is not what you want.

In order to do what you want, you'll need to check whether the two arrays have the same length, and that each member in each index is identical.

Assuming your array is filled with primitives—numbers and or strings—something like this should do

function arraysAreIdentical(arr1, arr2){
    if (arr1.length !== arr2.length) return false;
    for (var i = 0, len = arr1.length; i < len; i++){
        if (arr1[i] !== arr2[i]){
            return false;
        }
    }
    return true; 
}