I think I"m a little confused about how JS sort works and how the compare function uses the positive and negative numbers that are returned from it. I have this code:
const stripCommas = value =>
typeof value === "string" ? value.replace(/,/g, "") : value;
const compareStringNumbersWithCommasAndStrings = (option1, option2) =>
isNaN(stripCommas(option2)) - isNaN(stripCommas(option1)) ||
stripCommas(option1) - stripCommas(option2);
and this array:
var array = ["full", "no", '1,000', '3,000', 2, "may", 0]
and when this is run, this is the result:
array.sort(compareStringNumbersWithCommasAndStrings)
=> [ 'full', 'no', 'may', 0, 2, '1,000', '3,000' ]
So when "full" and "no" are passed into the compareStringNumnbersWithCommasAndStrings
function, both are NaN
so we get true - true
which is === 0
so we get 0 || NaN
which evaluates to NaN
which is equivalent to 0 apparently in a sort function so the elements do not change. That I understand.
But when we get to no
and 1,000
, the compare function will do true - false
in the first part before the ||
which evaluates to 1
and then no
- 1000
which evaluates to NaN
so then 1 || NaN
evaluates to 1
so shouldn't the two switch? Doesn't sort switch when the result is positive? The positive means the first option passed into the sort will be at a higher index than the second right?
Under the hood, what kind of sort is this? How many compares are being made?