Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort array of strings with negative and positive numbers

Tags:

javascript

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.

like image 674
Ali Ankarali Avatar asked Dec 18 '22 23:12

Ali Ankarali


2 Answers

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.

like image 184
Nina Scholz Avatar answered Dec 28 '22 23:12

Nina Scholz


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' ]
like image 25
bluelovers Avatar answered Dec 29 '22 00:12

bluelovers