![]() |
VOOZH | about |
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.
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
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.
[
{ gender: 'male', age: 22 },
{ gender: 'female', age: 25 },
{ gender: 'male', age: 30 }
]
Time complexity: O(n log n).
Space complexity: O(1).
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.
[
{ gender: 'male', age: 22 },
{ gender: 'female', age: 25 },
{ gender: 'male', age: 30 }
]
Time complexity: O(n log n).
Space complexity: O(1).