How to Sort an Array of Objects By Value in Javascript?

spot_img

Share This Post

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!

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Related Posts

How to Choose Best Lift Chair?

For people with physical disabilities and the elderly, getting...

NuWave Brio Air Fryer Review

Craving for some fried goods but scared of the...

Commercial Toaster: Top Picks with Buying Guide and FAQs

Commercial Toaster: Top Picks with Buying Guide and FAQs...

Best High-Velocity Blower Fans

Does your room feel so warm during the summer?...

10 Best Xbox One Gaming Chair: Buying Guide And Reviews

For some people, console gaming should have the right...

Best Gaming Chairs Under 200$

Whether you game as a hobby or happen to...
spot_img
- Advertisement -spot_img