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

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

For example, this array:

const arr = [1, 'fdf', 'afv', 6, 47, 7, 'svd', 'bdf', 9];
console.log("Original array:", arr);
Original array: [ 1, 'fdf', 'afv', 6, 47, 7, 'svd', 'bdf', 9 ]

Should look like this after sorting:

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

Implementation

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);
[
  1,     6,     7,
  9,     47,    'afv',
  'bdf', 'fdf', 'svd'
]

How the Sorting Logic Works

The main part of this code is the sorter function, which is a comparison function passed to Array.sort(). The callback function receives two arguments, both being elements of the array.

The function handles four possibilities:

  • Both a and b are numbers ? We place the smaller number before the bigger one using a - b

  • a is number but b is string ? We place the number (a) before string (b) by returning -1

  • a is string but b is number ? We place the number (b) before string (a) by returning 1

  • Both a and b are strings ? We check which string comes first alphabetically and place it before

Alternative Approach Using Array Filtering

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

// Separate numbers and strings, then sort each group
const numbers = arr.filter(item => typeof item === 'number').sort((a, b) => a - b);
const strings = arr.filter(item => typeof item === 'string').sort();

const sortedArray = [...numbers, ...strings];
console.log(sortedArray);
[ 1, 6, 7, 9, 47, 'afv', 'bdf', 'fdf', 'svd' ]

Conclusion

Both approaches achieve natural sorting by prioritizing numbers over strings. The custom comparator method is more memory-efficient, while the filtering approach is more readable and explicit about the separation logic.

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

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements