Separate Alphabets and Numbers from an Array using JavaScript



We have an array that contains some number literals and some string literals mixed, and we are required to write a sorting function that separates the two and the two types should also be sorted within.

The code for this sorting function will be −

Example

const arr = [1, 5, 'fd', 6, 'as', 'a', 'cx', 43, 's', 51, 7];
const sorter = (a, b) => {
   const first = typeof a === 'number';
   const second = typeof b === 'number';
   if(first && second){
      return a - b;
   }else if(first && !second){
      return -1;
   }else if(!first && second){
      return 1;
   }else{
      return a > b ? 1 : -1;
   }
};
arr.sort(sorter);
console.log(arr);

Output

The output in the console will be −

[
   1, 5, 6, 7,
   43, 51, 'a', 'as',
   'cx', 'fd', 's'
]
Updated on: 2020-08-20T06:45:24+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements