How to use Custom Sorting Function In Javascript

In this approach, we are using the Custom Sorting Function where the array is iterated and the adjacent elements are swapped by comparing their properties using localeCompare() method. This continues till no more swaps are required.

Syntax:

function function_name()
{
// sorting logic
}

Example: The below example uses the Custom Sorting Function to sort an array of objects based on a key in JavaScript.

Javascript
let arr = [
    { name: 'Arrays', topic: 'Data Structures' },
    { name: 'Recursion', topic: 'Algorithms' },
    { name: 'JavaScript', topic: 'Programming' }
];
function approach2Fn(arr, k) {
    let temp;
    do {
        temp = false;
        for (let i = 0; i < arr.length - 1; i++) 
        {
            if (arr[i][k].
                localeCompare(arr[i + 1][k]) > 0) 
            {
                [arr[i], arr[i + 1]] = 
                    [arr[i + 1], arr[i]];
                temp = true;
            }
        }
    } while (temp);
    return arr;
}
arr = approach2Fn(arr, 'name');
console.log(arr);

Output
[
  { name: 'Arrays', topic: 'Data Structures' },
  { name: 'JavaScript', topic: 'Programming' },
  { name: 'Recursion', topic: 'Algorithms' }
]

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() method
  • Using Custom Sorting Function
  • Using Lodash _.orderBy() Method
  • Using Intl.Collator

Similar Reads

Using sort() method

In this approach, we will use the sort() method with a custom comparator function that compares the name property of objects using localeCompare() method, which makes sure that the array is sorted alphabetically by the name key....

Using Custom Sorting Function

In this approach, we are using the Custom Sorting Function where the array is iterated and the adjacent elements are swapped by comparing their properties using localeCompare() method. This continues till no more swaps are required....

Using Lodash _.orderBy() Method

In this approach, we will use the Lodash _.orderBy() method. If orders are unspecified, then all values are sorted in ascending order. Otherwise, order of corresponding values specifies an order of desc for descending or asc for ascending sort....

Using Intl.Collator

The Intl.Collator object is a constructor for collators, which are objects that enable language-sensitive string comparison. This approach allows for more sophisticated sorting options, including case sensitivity and locale-specific rules....