Categories
JavaScript Answers

How to sort arrays numerically by object property value with JavaScript?

Spread the love

Sometimes, we want to sort arrays numerically by object property value with JavaScript.

In this article, we’ll look at how to sort arrays numerically by object property value with JavaScript.

How to sort arrays numerically by object property value with JavaScript?

To sort arrays numerically by object property value with JavaScript, we can use the array sort method.

For instance, we write

const sorted = myArray.sort((a, b) => a.distance - b.distance);

to call myArray.sort with a callback that returns a.distance - b.distance to return a new array that sort the entries in myArray by the value of the distance property of each object in ascending order.

Conclusion

To sort arrays numerically by object property value with JavaScript, we can use the array sort method.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *