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.
]
«N.B.» 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?
-
the function checks whether the two length are equals and, if so, if each element of the array equals the other, it will return true. That might make sense, though it will miss a case where objects order is not the same, but the content really is, like this case: jsfiddle.net/4ke1gdz0briosheje– briosheje2016年12月20日 10:15:27 +00:00Commented Dec 20, 2016 at 10:15
3 Answers 3
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.
2 Comments
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.
1 Comment
If you are talking about a shallow equal, then the function could be used (e.g. 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 (i.e. compare all values, objects and arrays in depth, recursively). You could implement this yourself, but if possible use a third party library like underscore.