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

Based on the following, you can sort elements of an array in ascending or descending order based on the length of each element:

Sort Array by Length of Elements in Ascending Order

To sort array elements with the shortest length first and the longest length last (i.e. in ascending order), you 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 Length of Elements in Descending Order

To sort array elements with the longest length first and the shortest length last (i.e. in descending order), you 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 (and was last revised ). Please show your love and support by sharing this post.