Especially in the frontend it happens quite often that you want to sort an array, an array with objects according to a certain pattern. Javascript has very performant and nice functions. But you can use these functions not only in the frontend. If you write your backend with NodeJS you will also appreciate the array functions of Javascript.
Goal: To sort an array of objects alphanumerically. Once ASC and once DESC. In this case by name. Imagine you have the following array:
const d = [
{
name: {
common: "Z"
}
},
{
name: {
common: "A"
}
},
{
name: {
common: "B"
}
}
];
We will sort with the sort() function. For alphanumeric sorting we also use the localCompare() function. To reverse the sorting we can use the reverse() function.
d.sort((a,b) => a.name.common.localeCompare(b.name.common))
console.log("asc",d);
console.log("asc",d.reverse());
And that was it for today 🙂