How to Sort a JavaScript Array Based on Length of Each Element?

Learn how you can sort an array based on each element's length in JavaScript

In this post, we will show you how you can sort elements of an array in ascending or descending order based on the length of each element.

Sort Array by Element Lengths in Ascending Order

To sort array elements with shortest length first and the longest length last (i.e. in ascending order), we can do the following:

const fruits = ['orange', 'melon', 'peach', 'apple', 'banana'];
const sortedFruits = fruits.sort((a, b) => a.length - b.length);

console.log(sortedFruits); // output: ['melon', 'peach', 'apple', 'orange', 'banana']

As you can see from the example above, when the strings are of the same length, they are ordered according to the order in the original array. If you would like to order them based on their natural ordering instead, then you can use the following instead:

const fruits = ['orange', 'melon', 'peach', 'apple', 'banana'];
const sortedFruits = fruits.sort((a, b) => a.length - b.length || a.localeCompare(b));

console.log(sortedFruits); // output: ['apple', 'melon', 'peach', 'orange', 'banana']

Sort Array by Element Lengths in Descending Order

To sort array elements with longest length first and the shortest length last (i.e. in descending order), we can do the following:

const fruits = ['orange', 'melon', 'peach', 'apple', 'banana'];
const sortedFruits = fruits.sort((a, b) => b.length - a.length);

console.log(sortedFruits); // output: ['orange', 'banana', 'melon', 'peach', 'apple']

As you can see from the example above, when the strings are of the same length, they are ordered according to the order in the original array. If you would like to order them based on their natural ordering instead, then you can use the following instead:

const fruits = ['orange', 'melon', 'peach', 'apple', 'banana'];
const sortedFruits = fruits.sort((a, b) => b.length - a.length || b.localeCompare(a));

console.log(sortedFruits); // output: ['orange', 'banana', 'peach', 'melon', 'apple']

Hope you found this post useful. It was published . Please show your love and support by sharing this post.