Firstly I could not find a question addressing the whole issue.
I used to compare arrays like this:
array.sort((a, b) => {
return a.localeCompare(b, undefined, {numeric: true, sensitivity: 'base'})
})
But I realized it does not work on an array like ['a', 'A', 'B', -1.50', '0', '1.50', '-2', '2']
.
The expected output would be: ['-2', '-1.50', '0', '1.50', '2', 'A', 'a', 'B']
.
I have some dirty ideas to achieve it. But maybe there is a clean and easy way.
You could prepend the comparison by taking the delta of the wanted properties. This saves the order for numerical values.
console.log(
['a', 'A', 'B', '-1.50', '0', '1.50', '-2', '2', 'D']
.sort((a, b) => a - b || a.localeCompare(b, undefined, {sensitivity: 'base'}))
);
numeric: true
option can be omitted for there won't be two numbers to compare at the left hand side of the expression.
const customSort = (array) => {
return array.sort((a, b) => {
let r = /^-?\d+(?:\.\d+)?$/;
if (r.test(a) && r.test(b))
{
return a - b;
}
return a.localeCompare(b, undefined, {numeric: true, sensitivity: 'base'})
})
}
console.log(customSort(['a', 'A', 'B', '-1.50', '0', '1.50', '-2', '2']));
// => [ '-2', '-1.50', '0', '1.50', '2', 'a', 'A', 'B' ]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With