How to use localeCompare for Strings and Numerical Comparison for Numbers In Javascript

Use localeCompare for string comparisons and numerical comparison for numbers. Convert both elements to strings and check if they’re both numbers. If so, compare numerically; otherwise, compare as strings for consistent sorting.

Example: In this example the function localeCompareSort sorts an array, prioritizing numeric values and then using locale comparison for strings,

JavaScript
function localeCompareSort(arr) {
    return arr.sort((a, b) => {
        if (!isNaN(a) && !isNaN(b)) {
            return a - b;
        } else {
            return String(a).localeCompare(String(b), undefined, { numeric: true });
        }
    });
}

let array = [3, 'apple', 1, 'banana', 2];
console.log(localeCompareSort(array)); 

Output
[ 1, 2, 3, 'apple', 'banana' ]




How to Sort an Array using JavaScript when Array Elements has Different Data Types ?

Sorting an array in JavaScript is the process of arranging the elements of the array in a certain order. Generally sorting in an array is to arrange the elements in increasing or decreasing order. It is a common task, however, when an array contains different data types such as numbers, strings, and booleans, sorting becomes a little more complicated. In this article, we will explore various approaches to sorting arrays with mixed data types.

There are different approaches to sorting an array with mixed data types in JavaScript. Let’s discuss each one of them.

Table of Content

  • Convert all data types to a common type before sorting
  • Using a custom comparison function
  • Use a third-party library
  • Using localeCompare for Strings and Numerical Comparison for Numbers

Convert all data types to a common type before sorting

This approach involves converting all data types in the array to a common type, such as string or number, before sorting. Once the array has been converted, we can use the built-in sort() method to sort the array.

 Example: In this example, we will convert all data types into strings and then use the sort() method.

Javascript
// Convert all data types to strings before sorting
const arr = [3, 'apple', true, 1, 'orange', false, 2];

const arr1 = arr.map(item => String(item));

arr1.sort();

console.log(arr1);

Output:

["1", "2", "3", "apple", "false", "orange", "true"]

Using a custom comparison function

Another approach is to write a custom comparison function that determines the sort order based on the data type. For example, we can sort strings alphabetically and numbers numerically.

Example: Here, we have used the custom comparison function. 

Javascript
const arr = [3, 'apple', true, 1, 'orange', false, 2];

// Write a custom comparison function
function compare(a, b) {
    const typeA = typeof a;
    const typeB = typeof b;

    if (typeA === typeB) {

        // If same type, compare values directly
        return a > b ? 1 : -1;
    } else {

        // If different types, sort by data type
        return typeA > typeB ? 1 : -1;
    }
}
arr.sort(compare);
console.log(arr);

Output:

[false, true, 1, 2, 3, 'apple', 'orange']

Use a third-party library

We can also use a third-party library such as Lodash or Underscore.js to sort arrays with mixed data types. These libraries provide a variety of sorting functions that can handle different data types.

Example: In this example, we will use const_= required(“lodash”) to import the lodash library in the file.

Javascript
// Requiring the lodash library 
const _ = require("lodash");

const arr = [3, 'apple', true, 1, 'orange', false, 2];

// Use Lodash library to sort by data type
const arr3 = _.sortBy(arr, [item => typeof item]);
console.log(arr3);

Output:

[1, 2, 3, false, true, "apple", "orange"]

Note: This code will not work in normal JavaScript because it requires the lodash library to be installed.

Similar Reads

Using localeCompare for Strings and Numerical Comparison for Numbers

Use localeCompare for string comparisons and numerical comparison for numbers. Convert both elements to strings and check if they’re both numbers. If so, compare numerically; otherwise, compare as strings for consistent sorting....