Computer >> Computer tutorials >  >> Programming >> Javascript

Sorting numbers in ascending order and strings in alphabetical order in an array in JavaScript


Problem

We are required to write a JavaScript function that takes in an array of numbers and strings. Our function is supposed to return a single array that has first the numbers sorted in ascending order, followed by the strings sorted in alphabetical order.

The values must maintain their original type.

Example

Following is the code −

const arr = [5, 8, 'car', 'dad', 'amber', 1, 12, 76, 'bat'];
const separateSort = (arr = []) => {
   const sorter = (a, b) => {
      if(typeof a === 'number' && typeof b === 'string'){
         return -1;
      };
      if(typeof a === 'string' && typeof b === 'number'){
         return 1;
      };
      if(typeof a === 'string' && typeof b === 'string'){
         return a.charCodeAt(0) - b.charCodeAt(0);
      };
      return a - b;
   };
   const res = arr.sort(sorter);
   return res;
};
console.log(separateSort(arr));

Output

Following is the console output −

[
   1, 5,
   8, 12,
   76, 'amber',
   'bat', 'car',
   'dad'
]