Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
371 views
in Technique[技术] by (71.8m points)

javascript - Compare arrays of objects, optimal way

I have two arrays. In each array I have objects with lots of properties but no methods. I need to see if array 1 is equal with array 2.

One way to do that would be to create a function that pass through each element of an array and compare each property of the object with the object in the similar position in the second array.

The problem is that the arrays are quite big and also each object has lots of properties. I was wandering if there could be another way. In C++ for example I could read memory... but I don't know how to do that in js.

I need to obtain the most optimal way since this is part of a function that is used often.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...