# Sorting numbers in ascending order and strings in alphabetical order in an array in JavaScript

In the realm of JavaScript programming, the ability to sort numbers in ascending order and strings in alphabetical order within an array holds paramount importance. Efficiently arranging elements in such a manner not only enhances the organization and readability of data but also plays a pivotal role in various data manipulation and analysis tasks. By harnessing the power of JavaScript's built-in sorting capabilities, developers can effortlessly arrange array elements in the desired order. In this article, we will explore the intricacies of sorting numbers in ascending order and strings in alphabetical order within an array, unveiling the underlying mechanisms and employing rarely used words to delve into the finer nuances of this fundamental programming technique.

## Problem Statement

The objective of this task is to devise a JavaScript function that arranges an array consisting of both numbers and strings in ascending order. The sorting process should prioritize numbers before strings, and within each category, the elements should be arranged in their respective order. The task requires the implementation of an algorithm that adheres to these requirements.

Sample Input −

An array with mixed numbers and strings: ["zebra", 21, "apple", 5, "orange", 13, "banana", 2]


Sample Output −

The array after sorting: [2, 5, 13, 21, "apple", "banana", "orange", "zebra"]


Note − The numbers are sorted in ascending order, followed by the strings arranged in alphabetical order.

## Approach

In this article, we are going to see a number of different ways to solve the above problem statement in JavaScript −

• Custom Sorting with Comparator Function

• Separate Arrays and Merge

## Method 1: Custom Sorting with Comparator Function

To sort an array with custom priority, define a comparator function that compares the elements based on their types and relative order. Use the Array.sort() method, passing the custom comparator function as an argument, to sort the array in place. The resulting sorted array will have numbers before strings based on the defined sorting order.

### Example

The compareElements function serves as a custom comparator for Array.sort(). Inside this function, we compare the types of 'a' and 'b' to determine their sorting order. If both are numbers or both are strings, we use a normal comparison to sort them in ascending order. If 'a' is a number and 'b' is a string, 'a' is prioritized by returning -1. Conversely, if 'a' is a string and 'b' is a number, 'b' is prioritized by returning 1. The unsorted 'arr' array contains both numbers and strings. Sorting it is achieved by calling arr.sort(compareElements). Finally, the sorted 'arr' is logged to the console.

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);


### Output

The following is the console output −

[ 3, 5, 10, 'apple', 'banana', 'carrot' ]


## Method 2: Separate Arrays and Merge

To separate numbers and strings, create two arrays and filter the original array based on type, storing elements accordingly. Sort the numbers array using Array.sort() with a numeric comparison function for ascending order. Sort the strings array with Array.sort() and a.localeCompare(b) for ascending order based on Unicode values. Merge the sorted arrays using the spread operator ([...numbers, ...strings]) to obtain the final sorted array.

### Example

Starting with an unsorted array "arr" containing numbers and strings, we create two separate arrays: "numbers" and "strings" using Array.filter(). The "numbers" array filters out number elements from "arr", while the "strings" array filters out string elements. We sort the "numbers" array using Array.sort() with a numeric comparison function (a, b) => a - b for ascending order. Similarly, we sort the "strings" array using Array.sort() with the a.localeCompare(b) function for ascending order based on Unicode values. Finally, we create "sortedArr" by merging "numbers" and "strings" arrays using the spread operator, and log it to the console.

let arr = [10, 'apple', 5, 'banana', 3, 'carrot'];
let numbers = arr.filter((element) => typeof element === 'number');
let strings = arr.filter((element) => typeof element === 'string');
numbers.sort((a, b) => a - b);
strings.sort((a, b) => a.localeCompare(b));
let sortedArr = [...numbers, ...strings];
console.log(sortedArr);


### Output

The following is the console output −

[ 3, 5, 10, 'apple', 'banana', 'carrot' ]


## Conclusion

In culminating the discussion on sorting numbers in ascending order and strings in alphabetical order within an array using JavaScript, we have explored an assortment of methodologies to accomplish this task with dexterity. By employing idiosyncratic algorithms and leveraging lesser-known functions, developers can efficaciously arrange the elements in the desired sequence. This heterogeneous amalgamation of numerical and lexical sorting not only exemplifies the versatility of JavaScript but also showcases its idiosyncratic power in manipulating diverse data types. In essence, the meticulous application of these arcane techniques can empower programmers to curate arrays that are impeccably organized, enabling seamless data processing and enhancing the overall functionality of their applications.

Updated on: 04-Aug-2023

1K+ Views