How to 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.

This approach uses a custom comparator function with JavaScript's sort() method to first separate numbers from strings, then sort each type individually.

Using Custom Sort Comparator

The code for this sorting function will be:

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;  // Both numbers: sort numerically
    }else if(first && !second){
        return -1;     // Number first, string second: number wins
    }else if(!first && second){
        return 1;      // String first, number second: number wins
    }else{
        return a > b ? 1 : -1;  // Both strings: sort alphabetically
    }
};

arr.sort(sorter);
console.log(arr);
[
   1, 5, 6, 7,
   43, 51, 'a', 'as',
   'cx', 'fd', 's'
]

How It Works

The custom comparator function checks the types of elements being compared:

  • Both numbers: Uses subtraction (a - b) for numerical sorting
  • Number vs String: Always places numbers before strings
  • Both strings: Uses string comparison for alphabetical sorting

Alternative Approach: Using Filter and Concat

You can also separate and sort using filter() method:

const arr = [1, 5, 'fd', 6, 'as', 'a', 'cx', 43, 's', 51, 7];

const numbers = arr.filter(item => typeof item === 'number').sort((a, b) => a - b);
const strings = arr.filter(item => typeof item === 'string').sort();

const result = numbers.concat(strings);
console.log(result);
[
   1, 5, 6, 7,
   43, 51, 'a', 'as',
   'cx', 'fd', 's'
]

Comparison

Method Performance Readability Memory Usage
Custom Comparator Single pass Moderate In-place sorting
Filter + Concat Multiple passes High Creates new arrays

Conclusion

The custom comparator approach is more efficient for large arrays as it sorts in place. The filter method is more readable but uses additional memory for temporary arrays.

Updated on: 2026-03-15T23:18:59+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements