DEV Community

Bruce Axtens
Bruce Axtens

Posted on

1 1

Sometimes JavaScript arrays don't compare

I must admit, I was expecting this to work

const arr = [];
arr.push(true);
arr.push(true);
arr.push(true);
if (arr === [true, true, true]) { ...
Enter fullscreen mode Exit fullscreen mode

but it doesn't, at least not in Microsoft JScript (ES3). Hmm, let's try Deno. Nope, doesn't work in Deno (V8) either.

Obviously, I missed something when learning JavaScript.

So I'm going with

if (arr.join() === [true, true, true].join()) { ...
Enter fullscreen mode Exit fullscreen mode

Not brilliant, but it'll do the job.

Top comments (2)

Collapse
 
bugmagnet profile image
Bruce Axtens • Edited

Your example works because {c:1,d:2} etc gets turned in to "[object Object]".

Collapse
 
miketalbot profile image
Mike Talbot ⭐

Well said! This is the danger in things that "appear" to work, but have subtle bugs.

For me just borrow someone else's deep compare (which will be faster as the moment it finds a difference it will exit). Lodash/Underscore has a deep compare, Sugar has one too.

The shortest naive way to do this is JSON.stringify both operands. But let's imagine that the two arrays are 50Mb long and differ on the first character - that would be an awfully slow process and a lot of memory thrashing.

SurveyJS custom survey software

Build Your Own Forms without Manual Coding

SurveyJS UI libraries let you build a JSON-based form management system that integrates with any backend, giving you full control over your data with no user limits. Includes support for custom question types, skip logic, an integrated CSS editor, PDF export, real-time analytics, and more.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay