Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I check if arrays are equal in javascript?

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?

like image 860
Shawn Avatar asked Oct 07 '12 15:10

Shawn


People also ask

Can you check if arrays are equal?

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.

How can we compare two arrays 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 can you tell if an array is identical?

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.


1 Answers

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

UPDATE

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
like image 76
RKumsher Avatar answered Oct 23 '22 00:10

RKumsher