Trying to understand why
[{a: "Foo"}, {a: "Bar"}].sort(({a}) => (a === 'Bar' ? -1 : 0))
Works in Chrome (puts {a: “Bar”} in 1st position), but not in Node
Any pointers?
Workaround is defaulting to 1 instead of 0:
[{a: "Foo"}, {a: "Bar"}].sort(({a}) => (a === 'Bar' ? -1 : 1))
-
Show this thread
-
Replying to @kaelig
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort#Description … indicates that 0 doesn’t guarantee original sort order. Though I agree, would be nice if the spec guaranteed a stable sort.
1 reply 0 retweets 0 likes -
Replying to @marcbaumbach
Kaelig Retweeted Mathias Bynens
Thanks! Apparently the answer to my question is here…https://twitter.com/mathias/status/1036626116654637057 …
Kaelig added,
Mathias BynensVerified account @mathiasArray.prototype.sort is now stable in@v8js v7.0 / Chrome 70!
Previously, V8 used an unstable QuickSort for arrays with more than 10 elements. Now, we use the stable TimSort algorithm.
Demo: https://mathiasbynens.be/demo/sort-stability … pic.twitter.com/zrynE48VcpShow this thread1 reply 0 retweets 2 likes -
Replying to @kaelig @marcbaumbach
Actually, something else is going on here. For arrays with ≤ 10 elements,
@v8js’s sort has always been stable. The problem in this case is the inconsistent comparison function: - if you compare 'Bar' with 'Foo' you get -1 - but if you compare 'Foo' with 'Bar' you get 01 reply 0 retweets 2 likes
A good comparison function always handles all possible cases (-1, 0, +1). E.g. [{ a: 'Foo' }, { a: 'Bar' }].sort(({a}, {b}) => { if (a === 'Bar' && a === b) return 0; if (a === 'Bar') return -1; if (b === 'Bar') return 1; return 0; });
Loading seems to be taking a while.
Twitter may be over capacity or experiencing a momentary hiccup. Try again or visit Twitter Status for more information.
JavaScript, HTML, CSS, HTTP, performance, security, Bash, Unicode, i18n, macOS.