How to use Compare Function In Javascript
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.
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' ]
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