Compare arrays of objects, optimal way

巧了我就是萌 提交于 2019-11-29 07:36:33
alex

Unless they are the same array instance, comparing the memory locations won't work in JavaScript (what happens when you do arr1 == arr2).

You would need to explicitly loop.

Some people use JSON.stringify() (watch out for the gotcha explained in the comments by pimvdb) on both arrays and compare the resulting strings to cheat, but serialising to a string and comparing sounds over fully expensive to me. However it works, so if there is no performance problem, go nuts! :)

You could also try toSource().

I would build my own comparative function that compares just enough that satisfies my idea of identical.

Zar Shardan

Converting your arrays to strings and then comparing the strings will have the same average and worst performance: O(n) (linear).

If you loop through your objects properties/arrays and abort on the 1st mismatch your worst performance will still be O(n) but your average performance might significantly improve unless the objects your'e comparing are usually identical. Either way, since this traversal wouldn't include creating any new objects and copying bytes around - even comparing identical composite objects/arrays (worst case) should still be faster than stringifying them.

As this answer suggests you could just use Underscore.js isEqual:

which according to docs: Performs an optimized deep comparison between the two objects, to determine if they should be considered equal

I'm pretty sure it will work for arrays too.

JQuery has a function called jQuery.param() which serializes objects

You can compare objects or arrays of objects like so,

$.param( originalObj ) == $.param( modifiedObj )

It's very powerful in conjuction with jQuery.extend() which can be used to clone objects

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!