Sorting Objects by Numeric Values using JavaScript

Given an array of objects, our task is to sort objects by numeric values in JavaScript. An object is a complex data type in JavaScript that allows us to store collections of key-value pairs.

Example:

Input: [ { gender : 'male' , age: 30 },
{ gender : 'female' ,age: 25 },
{gender : 'male' , age: 22 } ]

Output: [ { gender: 'male', age: 22 },
{ gender: 'female', age: 25 },
{ gender: 'male', age: 30 } ]

Explanation: Numeric values are now arranged in ascending order

Below are the approaches for Sorting objects by numeric values using JavaScript:

Table of Content

  • Using the sort() method
  • Using the localCompare() method

Using the sort() method

Define an array containing objects. Call the sort() method on the array of objects. Define a comparison function as an argument to sort(). This function takes two parameters, conventionally named a and b. Inside the comparison function, subtract the age property of object b from the age property of object a. This will result in sorting the objects in ascending order based on their age property.

Example: The below example shows Sorting objects by numeric values using the sort() method.

JavaScript
// Create an array of objects
let arrayOfObjects = [
    { gender: 'male', age: 30 },
    { gender: 'female', age: 25 },
    { gender: 'male', age: 22 }
];

// Use the sort() method with a comparison function
arrayOfObjects.sort((a, b) => a.age - b.age);

console.log(arrayOfObjects);

Output
[
  { gender: 'male', age: 22 },
  { gender: 'female', age: 25 },
  { gender: 'male', age: 30 }
]

Time complexity: O(n log n).

Space complexity: O(1).

Using the localCompare() method

Define an array containing objects. Call the sort() method on the array of objects. Define a comparison function as an argument to sort(). This function takes two parameters, conventionally named a and b, representing two elements from the array being compared. Inside the comparison function, use localeCompare to compare the string representations of the age properties of objects a and b.

Example: The example below shows Sorting objects by numeric values using the localCompare() method.

JavaScript
// Create an array of objects
let arrayOfObjects = [
    { gender: 'male', age: 30 },
    { gender: 'female', age: 25 },
    { gender: 'male', age: 22 }
];

// Use the sort() method with a comparison function
arrayOfObjects.sort((a, b) => 
    a.age.toString().localeCompare(b.age.toString()));

console.log(arrayOfObjects);

Output
[
  { gender: 'male', age: 22 },
  { gender: 'female', age: 25 },
  { gender: 'male', age: 30 }
]

Time complexity: O(n log n).

Space complexity: O(1).


Contact Us