Categories
JavaScript Answers

How to sort JavaScript array by two numeric fields?

Spread the love

Sometimes, we want to sort JavaScript array by two numeric fields.

In this article, we’ll look at how to sort JavaScript array by two numeric fields.

How to sort JavaScript array by two numeric fields?

To sort JavaScript array by two numeric fields, we use the || operator.

For instance, we write

const sortedArr = grouperArray.sort((a, b) => {
  return a.gSize - b.gSize || a.glow - b.glow;
});

to call grouperArray.sort with a callback that sorts by the values of the gSize and glow properties in each entries a and b.

We sort by gSize first and then glow.

Conclusion

To sort JavaScript array by two numeric fields, we use the || operator.

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 *