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
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.
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.
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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With