Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Compare two arrays regardless of order has siteeffects #475

Closed
relaxdays-bewerbung opened this issue Sep 30, 2021 · 4 comments · Fixed by #493
Closed

Compare two arrays regardless of order has siteeffects #475

relaxdays-bewerbung opened this issue Sep 30, 2021 · 4 comments · Fixed by #493

Comments

@relaxdays-bewerbung
Copy link

relaxdays-bewerbung commented Sep 30, 2021

Hi there,

your Sippet for comparing Arrays has an important downside. It sorts the original arrays, which is not the espected behaviour.
I suggest to fix it by cloning the arguments before sorting it or using Sets if number of sam items does not matter.

The current snippet:
// a and b are arrays
const isEqual = (a, b) => JSON.stringify(a.sort()) === JSON.stringify(b.sort());

// Examples
isEqual([1, 2, 3], [1, 2, 3]); // true
isEqual([1, 2, 3], [1, 3, 2]); // true
isEqual([1, 2, 3], [1, '2', 3]); // false

@phuocng
Copy link
Owner

phuocng commented Sep 30, 2021

Can you make a PR, @relaxdays-bewerbung ?

@elkarouani
Copy link
Contributor

elkarouani commented Dec 20, 2021

I didn't understand very well why you suggested cloning the arguments @relaxdays-bewerbung, what is exactly the issue with using the current snippet ?

@relaxdays-bewerbung
Copy link
Author

The issue is that a and b are different after the comparison a and b are different.

for example if you use this on
a = [1, 3, 2];
b = [3, 2, 1];
isEqual(a, b);

→ a and b both will be [1, 2, 3] afterwards.
a and be change during the function.

@elkarouani
Copy link
Contributor

Oh, I understand you now very well !

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging a pull request may close this issue.

3 participants