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

Array sort of undefined elements #2294

Closed
glemco opened this issue Nov 25, 2022 · 2 comments · Fixed by #2300
Closed

Array sort of undefined elements #2294

glemco opened this issue Nov 25, 2022 · 2 comments · Fixed by #2300

Comments

@glemco
Copy link

glemco commented Nov 25, 2022

At the moment it looks like undefined elements aren't correctly sorted in an array (they should always go on the bottom https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort), tried this in the ide:

>[1,undefined,5,undefined,2].sort((a,b)=>b-a)
=[ 5, 2, 1, undefined, undefined ]
>[1,undefined,5,undefined,2].sort((a,b)=>a-b)
=[ 1, undefined, 2, 5, undefined ] //this doesn't work!
>[1,undefined,5,undefined,2].sort()
=[ 1, 2, 5, undefined, undefined ]

Is that a desired behaviour/ something which would stay for some time? Should I make any assumption while doing this kind of sorting?

@gfwilliams
Copy link
Member

Well, it's not desired behaviour if it's not in the spec - hopefully someone could do a PR for this as it's probably not a big deal to fix, based on:

If compareFn is supplied, all non-undefined array elements are sorted according to the return value of the compare function (all undefined elements are sorted to the end of the array, with no call to compareFn).

Having said that, the behaviour with sparse arrays may be harder to fix I guess.

To be honest this is another bit of JS I don't really like though - it means that actually the compare function can't (for instance) choose to sort some items before undefined and some after.

@glemco
Copy link
Author

glemco commented Nov 25, 2022

Mmh I'm not sure how exactly is it implemented, but bringing all undefined instances down the array could be as simple as adding a case for isNaN(compareFn(a, b)), in this case if the compareFn accidentally handles undefined input (giving back a number), anything can be done.
Although not 100% compliant, I guess that could make everyone happy

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.

2 participants