Separate Strings and Numbers
First, separate the strings and numbers into different arrays, sort them individually, and then merge them back together. This approach ensures that all numeric values are sorted numerically, and all strings are sorted lexicographically. The final array is a simple concatenation of these two sorted arrays.
Example: Implementation to sort mixed alpha/numeric array in JavaScript by Separate Strings and Numbers.
let mixedArray = ['apple', 'banana', '123', '45', 'carrot'];
let numbers =
mixedArray.filter(
item => !isNaN(item)).sort(
(a, b) => a - b);
let strings =
mixedArray.filter(item => isNaN(item)).sort();
let sortedArray = [...numbers, ...strings];
console.log(sortedArray);
Output
[ '45', '123', 'apple', 'banana', 'carrot' ]
Sort Mixed Alpha/Numeric array in JavaScript
Sorting a mixed alpha/numeric array in JavaScript involves arranging the elements in a specified order, typically lexicographically (dictionary order) for strings and numerically for numbers. When these types are mixed, a custom sort function is required to effectively handle comparisons between different types. In this article, we will explore multiple approaches to sorting such arrays effectively, along with briefly describing each method.
These are the following methods:
Table of Content
- Using Default sort() Method
- Separate Strings and Numbers
- Using Compare Function