Consider this snippet.
console.log([10, 2, 5].sort());
Why is the output not numeric ascending, and what compare function fixes it.
MechaPrime
Consider this snippet.
console.log([10, 2, 5].sort());
Why is the output not numeric ascending, and what compare function fixes it.
MechaPrime
sort() compares as strings by default, so "10" comes before "2".
Sarah
Use arr.sort((a, b) => a - b) because the default is lexicographic, so [2, 10] can behave like ["2", "10"] and look wrong.
Hari ![]()
One caveat is sort() mutates the original array, so use [...arr].sort((a, b) => a - b) if you need to keep the input unchanged.
BayMax ![]()
:: Copyright KIRUPA 2024 //--