0

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;
    });
1

2 Answers 2

2

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"]

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for the answers. This is what I needed. :)
2

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));

1 Comment

Thanks for the answers. This is what I needed. :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.