Categories
JavaScript Answers

How to sort a JavaScript array based on the length of each element?

Spread the love

To sort a JavaScript array based on the length of each element, we call the sort method.

For instance, we write

const sorted = arr.sort((a, b) => {
  return b.length - a.length;
});

to call arr.sort with a callback that subtracts the length property values of b and a to return an array with the strings in arr sorted by length in descending order.

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 *