Let’s assume we have the following array of objects:
const data = {
users:[
{
id: 15,
name: "Zeddy Zebra"
},
{
id: 25,
name: "Naggy Newman"
},
{
id: 3,
name: "Gerry Giraffe"
},
]
};
Let’s say that we want to sort the names in those objects in ascending alphabetical order. Here’s how we would go about that:
const dataSort = data.users.sort((a,b) => {
if(a.name > b.name) {
return 1;
}
if(a.name < b.name) {
return -1;
}
return 0;
});
In the snippet above, we are taking to names from the array of objects and comparing them. If the name in a
is greater than the name in b
, it means sort b
before a
(return 1)
. If a
is less than b
(return -1)
, then sort a
before b
. If neither of them is either >
or <
, then the order prior to using sort
is kept as is (return 0)
.
Our output would be as follows after sorting:
[{
id: 3,
name: "Gerry Giraffe"
}, {
id: 25,
name: "Naggy Newman"
}, {
id: 15,
name: "Zeddy Zebra"
}]