How to use the localCompare() method In Javascript
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.
// 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).
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