简体   繁体   中英

Javascript - Check if two arrays are equal when arrays contain an object and an array

Lets say I have an array with following structure inside:

applications = [
    {
        source : {},
        highlight : []
    },
    {
       source : {},
       highlight : []
    },

    // More objects with same structure as objects above. 
]

Sometime, the array structure can be like following:

  applications = [
    {
        source : {}
    },
    {
       source : {}
    },

    // More objects with same structure as objects above. 
]

«NB» source and highlight have content, but now shown here.

Lets further say that I want to compare the two arrays above(with content). I want to specific check if they are equal.

A famous function for doing it, is this one:

arraysEqual(arr1, arr2) {
    if (arr1.length !== arr2.length)
        return false;
    for (var i = arr1.length; i--;) {
        if (arr1[i] !== arr2[i])
            return false;
    }
    return true;
}

I want to be sure, if this function will help me to decide whether the arrays are equal or not?

Here's the simple way...

JSON.stringify(arr1) == JSON.stringify(arr2)

The issue with the arraysEqual function you identify is that it would only work if the items in arr1 and arr2 were type String or Number (or Boolean), ie { source: 1 } is != { source: 1 }, because although they have the same content, they are different Objects.

Using Lodash method _.isEqual could be an option:

var object = { 'a': 1 };
var other = { 'a': 1 };

_.isEqual(object, other);
// => true

object === other;
// => false

Benefits:

  • Trustable
  • Makes a deep comparison
  • If you don't want to load the whole library you can add just this method .

I don't like to use Lodash for everything and do it in Vanilla JS in general, but in these cases I think it's worth using a library.

If you are talking about a shallow equal, then the function could be used (eg when comparing arrays like ['a', 4, 'b']).

This is however not likely what you want because of the data inside the arrays which consists (according to your example) objects and arrays.

If you want the data from each array to be exactly the same, you need a deep equal (ie compare all values, objects and arrays in depth, recursively). You could implement this yourself, but if possible use a third party library like underscore .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM