Nikhil Bharadwaj
Nikhil Bharadwaj

Reputation: 917

Javascript array sort for regular strings and strings of numbers

I have an array that could be either just a list of strings or it could be just a list of strings of numbers, i.e array could be like below

let array = ['abc','def','aef','gfh']
             or
let array = ['123','456','192','412']

I want to have sort function that can handle the natural sort in either of these case, below code doesn't seem to handle the string of numbers, is there a way to handle this?

    array.sort((a,b) => {
        if(a > b) return 1;
        if(a < b) return -1;
        return 0;
    });

Upvotes: 0

Views: 78

Answers (2)

palaѕн
palaѕн

Reputation: 73896

You can do this using String#localeCompare() method like:

let array = ['abc', 'def', 'aef', 'gfh']
array.sort((a, b) => a.localeCompare(b, undefined, { numeric: true }));
console.log(array)

array = ['123', '456', '192', '412', '5']
array.sort((a, b) => a.localeCompare(b, undefined, { numeric: true }));
console.log(array)
.as-console-wrapper { max-height: 100% !important; top: 0; }

As mentioned in the docs, for numeric sorting we just need to use {numeric: true} option.

// by default, "2" > "10"
console.log(["2", "10"].sort((a,b) => a.localeCompare(b))); // ["10", "2"]

// numeric using options:
console.log(["2", "10"].sort((a,b) => a.localeCompare(b, undefined, {numeric: true})));
// ["2", "10"]

Upvotes: 2

Fullstack Guy
Fullstack Guy

Reputation: 16908

You can check whether the element in the array is a number or a string in the sort function.

The isNaN(string) check would tell you if it is not a number:

function sortNumOrStr(array) {
  return array.sort((a, b) => isNaN(a) ? a.localeCompare(b) : +a - b);
}

let array = ['abc', 'def', 'aef', 'gfh']
console.log(sortNumOrStr(array));
array =  ['123', '456', '-90', '192', '412'];
console.log(sortNumOrStr(array));

Upvotes: 2

Related Questions