Skip to content

Compare two arrays regardless of order has siteeffects #475

@relaxdays-bewerbung

Description

@relaxdays-bewerbung

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

Activity

phuocng

phuocng commented on Sep 30, 2021

@phuocng
Owner

Can you make a PR, @relaxdays-bewerbung ?

elkarouani

elkarouani commented on Dec 20, 2021

@elkarouani
Contributor

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

relaxdays-bewerbung commented on Dec 22, 2021

@relaxdays-bewerbung
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

elkarouani commented on Dec 22, 2021

@elkarouani
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

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

      Development

      Participants

      @elkarouani@relaxdays-bewerbung@phuocng

      Issue actions

        Compare two arrays regardless of order has siteeffects · Issue #475 · phuocng/1loc