We might need to sort the data once we’ve added data to our Javascript arrays. Javascript makes it rather simple to sort a conventional array, but what if you have an array of objects? That adds a little complexity to the situation.
We’ll need to compare the values recursively in order to sort it out. Fortunately, javascript makes this simple. Let’s look at how to sort an array of items in javascript according to value.
Sorting an Array of Objects by Value
Imagine that we have a list of workers stored in an array of objects.
const employees = [
{ firstName: 'Bill', lastName: 'Cooper', age: 43},
{ firstName: 'James', lastName: 'River', age: 23},
{ firstName: 'Jill', lastName: 'Randell', age: 34},
{ firstName: 'Phillip', lastName: 'Morgan', age: 38},
]
We want the ages on this list to be listed from youngest to oldest. How are we going to do that?
The solution is actually rather straightforward. We can employ the sort built-in Array sort(). Let’s examine its application.
employees.sort((a, b) => (a.age > b.age) ? 1 : -1)
The “compareFunction” is the name of our sorting function. One element will be compared to another in it. It will check to verify if a is greater than b in this instance. With the youngest age at index 0, that example will arrange the array in ascending order.
Now, when we output our array, it will seem as follows:
[
{ firstName: 'James', lastName: 'River', age: 23},
{ firstName: 'Jill', lastName: 'Randell', age: 34},
{ firstName: 'Phillip', lastName: 'Morgan', age: 38},
{ firstName: 'Bill', lastName: 'Cooper', age: 43},
]
We could just use this function to make the order downward instead of ascending.
employees.sort((a, b) => (a.age < b.age) ? 1 : -1)
The oldest age currently has a 0 index. If you wish to arrange it alphabetically, you may do so using the same technique. Simply alter the attribute you plan to compare.
Check out the sort() method’s official documentation for more information on how it functions inside out. Coding is fun!