phuocng / 1loc

What's your favorite JavaScript single LOC (line of code)?

Home Page:https://phuoc.ng/collection/1-loc

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Compare two arrays regardless of order has siteeffects

relaxdays-bewerbung opened this issue · comments

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

Can you make a PR, @relaxdays-bewerbung ?

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

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.

Oh, I understand you now very well !