VOOZH about

URL: https://www.geeksforgeeks.org/javascript/sorting-objects-by-numeric-values-using-javascript/

⇱ Sorting Objects by Numeric Values using JavaScript - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Sorting Objects by Numeric Values using JavaScript

Last Updated : 5 Aug, 2025

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:

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.


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.


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

Time complexity: O(n log n).

Space complexity: O(1).

Comment