Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Sorting numbers in ascending order and strings in alphabetical order in an array in JavaScript
In JavaScript, sorting arrays that contain both numbers and strings requires a custom approach since the default sort() method converts all elements to strings. This article explores two effective methods to sort mixed arrays with numbers first (ascending) followed by strings (alphabetical).
Problem Statement
We need to create a JavaScript function that sorts an array containing both numbers and strings. The requirements are:
- Numbers should appear before strings
- Numbers should be sorted in ascending order
- Strings should be sorted alphabetically
Sample Input:
["zebra", 21, "apple", 5, "orange", 13, "banana", 2]
Sample Output:
[2, 5, 13, 21, "apple", "banana", "orange", "zebra"]
Method 1: Custom Sorting with Comparator Function
This approach uses a custom comparator function with Array.sort() to handle different data types appropriately.
function compareElements(a, b) {
// If both elements are numbers or both are strings, perform normal comparison
if ((typeof a === 'number' && typeof b === 'number') || (typeof a === 'string' && typeof b === 'string')) {
return a < b ? -1 : a > b ? 1 : 0;
}
// If a is a number and b is a string, prioritize a (numbers before strings)
if (typeof a === 'number' && typeof b === 'string') {
return -1;
}
// If a is a string and b is a number, prioritize b (numbers before strings)
if (typeof a === 'string' && typeof b === 'number') {
return 1;
}
}
let arr = [10, 'apple', 5, 'banana', 3, 'carrot'];
arr.sort(compareElements);
console.log(arr);
[ 3, 5, 10, 'apple', 'banana', 'carrot' ]
Method 2: Separate Arrays and Merge
This method separates numbers and strings into different arrays, sorts them individually, then combines them.
let arr = [10, 'apple', 5, 'banana', 3, 'carrot']; // Separate numbers and strings let numbers = arr.filter(element => typeof element === 'number'); let strings = arr.filter(element => typeof element === 'string'); // Sort each array separately numbers.sort((a, b) => a - b); // Numeric sort strings.sort((a, b) => a.localeCompare(b)); // Alphabetical sort // Merge the sorted arrays let sortedArr = [...numbers, ...strings]; console.log(sortedArr);
[ 3, 5, 10, 'apple', 'banana', 'carrot' ]
Comparison of Methods
| Method | Performance | Readability | Memory Usage |
|---|---|---|---|
| Custom Comparator | Good - Single sort pass | Medium - Complex logic | Low - In-place sorting |
| Separate and Merge | Medium - Multiple operations | High - Clear steps | Higher - Creates new arrays |
Key Points
- The custom comparator method is more memory-efficient as it sorts in place
- The separate arrays method is more readable and easier to understand
- Both methods handle the type checking correctly to ensure proper ordering
- For string sorting,
localeCompare()is preferred over simple comparison operators
Conclusion
Both methods effectively sort mixed arrays with numbers before strings. Choose the custom comparator for better performance or the separate arrays approach for clearer, more maintainable code.
