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.