Have a look at this code sample or go to the jsfiddle
function printRelation(a, b, out) {
var text;
if (a === b) {
text = "a === b";
} else if (a == b) {
text = "a == b";
} else {
text = "a != b";
}
$('#' + out).text(text);
}
var a = [0, 0, 2], b = a;
printRelation(a, b, 'out1');
a = [0, 0, 2];
b = [0, 0, 2];
printRelation(a, b, 'out2');
I would have expected both tests to output a === b
, but only the first one does. The second one outputs a != b
. Can anyone explain this behaviour? How can I efficiently compare arrays in javascript?
The Arrays. equals() method checks the equality of the two arrays in terms of size, data, and order of elements. This method will accept the two arrays which need to be compared, and it returns the boolean result true if both the arrays are equal and false if the arrays are not equal.
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.
Check if two arrays are equal or not using Sorting Then linearly compare elements of both the arrays. If all are equal then return true, else return false.
You can use the Underscore.js library's isEqual method.
http://underscorejs.org/#isEqual
Performs an optimized deep comparison between the two objects, to determine if they should be considered equal.
var moe = {name : 'moe', luckyNumbers : [13, 27, 34]};
var clone = {name : 'moe', luckyNumbers : [13, 27, 34]};
moe == clone;
=> false
_.isEqual(moe, clone);
=> true
Lodash is inspired by underscore, but nowadays is superior solution
https://lodash.com/docs/#isEqual
Performs an optimized deep comparison between the two objects, to determine if they should be considered equal.
var object = { 'a': 1 };
var other = { 'a': 1 };
_.isEqual(object, other);
// => true
object === other;
// => false
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