Sort Mixed Alpha/Numeric array in JavaScript
Last Updated :
14 May, 2024
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:
Using Default sort( )
Method
JavaScript’s built-in sort()
method converts elements to strings and sorts them lexicographically (dictionary order).
Example: Implementation to sort mixed alpha/numeric array in JavaScript.
JavaScript
let mixedArray = ['apple', 'banana', '123', '45', 'carrot'];
mixedArray.sort();
console.log(mixedArray);
Output[ '123', '45', 'apple', 'banana', 'carrot' ]
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.
JavaScript
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' ]
Using Compare Function
Use a single compare function to handle both types, ensuring that numbers are sorted numerically and strings lexicographically within a single array. The compare function checks if both elements are numbers, both are strings, or one is a number and the other is a string. It applies numerical sorting if both are numbers and lexicographical sorting if both are strings. If one is a number and the other is a string, it ensures numbers come before strings in the sorted array.
Example: Implementation to sort mixed alpha/numeric array in JavaScript Unified Compare Function.
JavaScript
let mixedArray = ['apple', 'banana', '123', '45', 'carrot'];
mixedArray.sort((a, b) => {
if (!isNaN(a) && !isNaN(b)) {
// Both are numbers
return a - b;
} else if (!isNaN(a)) {
// 'a' is a number and 'b' is a string
return -1;
} else if (!isNaN(b)) {
// 'a' is a string and 'b' is a number
return 1;
} else {
// Both are strings
return a.localeCompare(b);
}
});
console.log(mixedArray);
Output[ '45', '123', 'apple', 'banana', 'carrot' ]
Similar Reads
JavaScript - Sort a Numeric Array Here are some common methods to Sort Numeric Array using JavaScript. Please note that the sort function by default considers number arrays same as an array of stings and sort by considering digits as characters.Using sort() with a Comparison Function - Most UsedThe sort() method in JavaScript, when
2 min read
Sort an Array in JavaScript This article will show you how to sort a JS array.1. Using array.sort() Method To sort an array in JavaScript, we can use array.sort() method. This method sorts the elements alphabetically in ascending order.JavaScriptlet arr = ["JS", "HTML", "CSS"]; arr.sort() console.log(arr);Output[ 'CSS', 'HTML'
3 min read
JavaScript Array sort() Method The JS array.sort() method rearranges the array elements alphabetically and returns a sorted array. It does not create a new array but updates the original array.Sorting Array of StringsJavaScript// Original array let ar = ["JS", "HTML", "CSS"]; console.log(ar); // Sorting the array ar.sort() consol
4 min read
Sort An Array Of Arrays In JavaScript The following approaches can be used to sort array of arrays in JavaScript.1. Using array.sort() Method- Mostly UsedJS array.sort() is used to sort and update the original array in ascending order.JavaScriptlet arr = [[3, 2], [1, 4], [2, 5], [2, 0]]; arr.sort(); console.log(arr);Output[ [ 1, 4 ], [
2 min read
How to get median of an array of numbers in JavaScript ? In this article, we will see how to find the median of an array using JavaScript. A median is a middle value in a given set of numbers or data. Examples: Input arr1 : [1 4 7 9]Output : 5.5Explanation : The median of the two sorted array is the middle elements which is 5 if the arrayLength =arr1.leng
3 min read
JavaScript - Sort an Array in Reverse Order in JS JS array.sort() Method sorts the array in ascending order. We can make it descending or reverse order using array.reverse() method. Below are the following ways to sort an array in reverse order:1. Using array.sort() with array.reverse()First, sort the given array of strings using JS array.sort() me
2 min read
JavaScript Array toSorted() Method The JS arr.toSorted() method rearranges the array elements alphabetically and returns a new sorted array.Sorting Array of StringsJavaScriptconst arr = ["JS", "HTML", "CSS"]; const arr1 = arr.toSorted(); console.log(arr); console.log(arr1);Output[ 'JS', 'HTML', 'CSS' ][ 'CSS', 'HTML', 'JS' ]Array.toS
3 min read
How to Sort a Multidimensional Array in JavaScript by Date ? Sorting a Multidimensional Array by date consists of ordering the inner arrays based on the date values. This needs to be done by converting the date representation into the proper comparable formats and then applying the sorting function to sort the array in ascending or descending order. Below are
2 min read
JavaScript- Merge two Sorted Arrays These are the following ways to merge two sorted arrays: 1. Using Two Pointers (Efficient For Large Arrays)This approach involves using two pointers, one for each array, and comparing their elements as you iterate through them. This method works efficiently in O(n + m) time, where n and m are the le
3 min read
How to Sort an Array of Objects Based on a Key in JavaScript ? In JavaScript, sorting an array of objects based on the key consists of iterating over the array, applying the sort() method or other approaches, and arranging the array in the desired sorting order. Table of Content Using sort() methodUsing Custom Sorting FunctionUsing Lodash _.orderBy() MethodUsin
3 min read