Natural Sort in JavaScript


We have an array that contains some numbers and some strings, we are required to sort the array such that the numbers get sorted and get placed before every string and then the string should be placed sorted alphabetically.

For example

Let’s say this is our array −

const arr = [1, 'fdf', 'afv', 6, 47, 7, 'svd', 'bdf', 9];

The output should look like this −

[1, 6, 7, 9, 47, 'afv', 'bdf', 'fdf', 'svd']

Therefore, let’s write the code for this −

const arr = [1, 'fdf', 'afv', 6, 47, 7, 'svd', 'bdf', 9];
const sorter = (a, b) => {
   if(typeof a === 'number' && typeof b === 'number'){
      return a - b;
   }else if(typeof a === 'number' && typeof b !== 'number'){
      return -1;
   }else if(typeof a !== 'number' && typeof b === 'number'){
      return 1;
   }else{
      return a > b ? 1 : -1;
   }
}
arr.sort(sorter);
console.log(arr);

The output in the console will be −

[
   1, 6, 7,
   9, 47, 'afv',
   'bdf', 'fdf', 'svd'
]

Updated on: 09-Oct-2020

575 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements