Categories
JavaScript Answers

How to sort array of objects by a boolean property with JavaScript?

Spread the love

Sometimes, we want to sort array of objects by a boolean property with JavaScript.

In this article, we’ll look at how to sort array of objects by a boolean property with JavaScript.

How to sort array of objects by a boolean property with JavaScript?

To sort array of objects by a boolean property with JavaScript, we can use the Number function.

For instance, we write

const a = [
  false,
  true,
  true,
  true,
  true,
  true,
  true,
  true,
  true,
  true,
  true,
  true,
  true,
  true,
  false,
  true,
  false,
  false,
  false,
  false,
  false,
  false,
  false,
  false,
  false,
  false,
  false,
  false,
  false,
  false,
  false,
  false,
  false,
  false,
  false,
  false,
  false,
  false,
  false,
  false,
  false,
  false,
  false,
  false,
  false,
  false,
  false,
  false,
];
const sorted = a.sort((x, y) => Number(x) - Number(y));
console.log(a);

to call a.sort with a callback that converts the booleans x and y to numbers.

And we subtract them so that we sort items with true coming before false.

Conclusion

To sort array of objects by a boolean property with JavaScript, we can use the Number function.

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 *