To sort an array of objects by property, you can use sort() method of JavaScript. You can pass comparison function that compares two objects based on the property you want to sort by.
const users = [
{ name: "Alice", age: 25 },
{ name: "Bob", age: 30 },
{ name: "Charlie", age: 20 }
];
let sortedUsers = users.sort((a, b) => a.age-b.age);
console.log(sortedUsers);
Output
[{
age: 20,
name: "Charlie"
}, {
age: 25,
name: "Alice"
}, {
age: 30,
name: "Bob"
}]
To sort by name, you can use localeCompare() method, for ex
const users = [
{ name: "Charlie", age: 25 },
{ name: "Alice", age: 30 },
{ name: "Bob", age: 20 }
];
let sortedUsers = users.sort((a, b) => a.name.localeCompare(b.name));
console.log(sortedUsers);
Output
[{
age: 30,
name: "Alice"
}, {
age: 20,
name: "Bob"
}, {
age: 25,
name: "Charlie"
}]
Similar Reads
- JavaScript – Sum of Digits of a NumberIn this article, we will learn how to find the sum of digits of a given number. The sum of digits can be obtained by… Read more: JavaScript – Sum of Digits of a Number
- JavaScript – Reverse a StringIn this article, we’ll look at three basic ways to reverse a string in JavaScript: the built-in reverse() method, a for loop, and the spread operator + reverse(). Using… Read more: JavaScript – Reverse a String
- JavaScript – Find the Intersection of Two ArraysIn this article, we will explore how to implement a function in JavaScript to find the intersection (Common Elements) of two arrays. The problem Write… Read more: JavaScript – Find the Intersection of Two Arrays
- JavaScript – Convert an array to an objectThere are many ways to convert an array to an object in JavaScript. Let’s explore some of the common approaches – Using reduce() In the… Read more: JavaScript – Convert an array to an object
- JavaScript – Shuffle an array in a random orderTo shuffle an array in random order in JavaScript, you can use the sort() function with Math.random() or use the map() & sort() function. Let’s… Read more: JavaScript – Shuffle an array in a random order
- JavaScript – Add elements to a JSON ArrayIn JavaScript, you can add elements to a JSON array in several ways. Here are some common methods : Using push method The push() method in JavaScript… Read more: JavaScript – Add elements to a JSON Array
- JavaScript – Remove specific property from an objectTo remove a specific property from an object in JavaScript, you can use the delete operator or create a new object without those properties. Let’s explore some… Read more: JavaScript – Remove specific property from an object
- JavaScript – Convert an object to an arrayThere are many ways to convert an object to an array in JavaScript. Let’s explore some common approaches. Convert Object Values to Array If you… Read more: JavaScript – Convert an object to an array