How to separate alphabets and numbers from an array using JavaScript

JavascriptWeb DevelopmentObject Oriented Programming

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'
]
raja
Published on 20-Aug-2020 06:44:57
Advertisements