Bacancy Technology
Bacancy Technology represents the connected world, offering innovative and customer-centric information technology experiences, enabling Enterprises, Associates and the Society to Riseâ„¢.
12+
Countries where we have happy customers
1050+
Agile enabled employees
06
World wide offices
12+
Years of Experience
05
Agile Coaches
14
Certified Scrum Masters
1000+
Clients projects
1458
Happy customers
Artificial Intelligence
Machine Learning
Salesforce
Microsoft
SAP
February 15, 2024
In JavaScript, you can sort an array of objects by their property values using the Array.sort() method along with a custom sorting function.
Let’s say you have an array of objects like this:
let arrayOfObjects = [ { name: 'John', age: 30 }, { name: 'Alice', age: 25 }, { name: 'Bob', age: 35 } ];
If you want to sort the array of objects based on a numeric property (e.g., age), you can use a comparison function inside sort():
arrayOfObjects.sort((a, b) => a.age - b.age);
This will sort the array in ascending order based on the age property.
If you want to sort based on a string property (e.g., name), you can use localeCompare() inside the comparison function:
arrayOfObjects.sort((a, b) => a.name.localeCompare(b.name));
This will sort the array alphabetically based on the name property.
To sort in descending order, you can switch a and b in the comparison function:
arrayOfObjects.sort((a, b) => b.age - a.age); // For numeric property (e.g., age) // OR arrayOfObjects.sort((a, b) => b.name.localeCompare(a.name)); // For string property (e.g., name)
The sort() method sorts the array in place and mutates the original array. If you want to avoid mutating the original array, you can create a new sorted array using the spread operator or Array.slice():
// Sorting by age without mutating the original array const sortedByAge = [...arrayOfObjects].sort((a, b) => a.age - b.age); // Sorting by name without mutating the original array const sortedByName = arrayOfObjects.slice().sort((a, b) => a.name.localeCompare(b.name));