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

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']

This post was published (and was last revised ) by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.