Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 
like image 571
Sudharsan S Avatar asked Mar 14 '14 03:03

Sudharsan S


People also ask

How do you compare two arrays are equal or not in JS?

While JavaScript does not have an inbuilt method to directly compare two arrays, it does have inbuilt methods to compare two strings. Strings can also be compared using the equality operator. Therefore, we can convert the arrays to strings, using the Array join() method, and then check if the strings are equal.

How do you check if an array is equal to another array JavaScript?

To conclude, to compare arrays to check for equality, Lodash's isEqual() function is the way to go if you need all the bells and whistles of checking that objects have the same class. The JSON. stringify() approach works well for POJOs, just make sure you take into account null.

How do you compare two arrays if they are equal or not?

Check if two arrays are equal or not using Sorting Follow the steps below to solve the problem using this approach: Sort both the arrays. Then linearly compare elements of both the arrays. If all are equal then return true, else return false.


2 Answers

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.

like image 141
xdazz Avatar answered Oct 24 '22 19:10

xdazz


A less robust approach, but it works.

a = [2, 4, 5].toString(); b = [2, 4, 5].toString();  console.log(a===b); 
like image 44
user2421180 Avatar answered Oct 24 '22 19:10

user2421180