Sort Array of numeric & alphabetical elements (Natural Sort) JavaScript

JavascriptWeb DevelopmentObject Oriented Programming

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

For example −

This array after being sorted

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

Should look like this −

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

So, let’s write the code for this −

Example

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

Output

The output in the console will be −

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

Understanding the code −

The main part of this code is the sorter function, we know the callback function receives two arguments, both being the elements of the array.

Now we have four possibilities −

  • Both a and b are number → in this case we place the smaller number before the bigger

  • a is number but b is string → in this case we place the number (a) before string (b) as asked in the question.

  • a is string but b is number → in this case we place b before a

  • Both a and b are string → we check for the string that is alphabetically smaller i.e., comes before and places it before.

raja
Published on 19-Aug-2020 06:49:41

Advertisements