I have 2 observable arrays and within an if statement I want to do something only if the arrays are identical, is there any way to do this without looping through each?
Asked
Active
Viewed 262 times
0
-
Possible duplicate of [How to compare arrays in JavaScript?](https://stackoverflow.com/questions/7837456/how-to-compare-arrays-in-javascript) – Regis Portalez Sep 29 '17 at 14:37
2 Answers
2
Generally speaking, no. You cannot differentiate an apple from an orange if you don't see that the apple is an apple and the orange is an orange. You can, however, use heuristics/shortcuts, such as:
- Is the length of them equal? If not, then sure as hell, they are different.
- Does the order of elements matter? If yes, the first time you find a difference, you can terminate early with a negative answer.
Also a few things to note about the JSON approach posted in the other answer:
- It will not work if the order of items does not matter
- It will not work if any object in the array contains circular references
- It will not work if there are objects with the same properties and values but the keys are in a different order. For example:
{ a: 1, b: 2 }
and{ b: 2, a: 1 }
would normally be considered equal (unless your explicit purpose is object reference equality) but the JSON representation of these will be different. - It is slower, because just to produce the JSONs you need to iterate over all properties anyway and you need to iterate over the individual characters of the JSON to perform the comparison.
So to sum it up, while it might be a tiny bit shorter and easier to read, there are several caveats, which might or might not mean a problem depending on your requirements.

Balázs
- 2,929
- 2
- 19
- 34
1
You can call ko.toJSON on both arrays and then compare the json strings that are returned. Functionally that's probably just as much work if not more for the processor as looping through both arrays but it does look cleaner if that's all you're going for.
isEqual = ko.toJSON(aryA) === ko.toJSON(aryb)

Jason Spake
- 4,293
- 2
- 14
- 22
-
-
Tbh, there are several problems with this approach. See the other answer. – Balázs Sep 30 '17 at 10:55