JavaScript Code


How to sort array of strings based on string length in JavaScript?


Sort array of strings based on string length in JavaScript

In this tutorial, you are given an array of strings. You should write a JavaScript program to sort the array in ascending order based on the length of the strings. String with smaller length is lesser than the string with relatively greater length.

Solution

To sort an array of strings based on length, use array sort() method and pass a comparing function. The comparing function must take two strings as arguments, and return the difference of the lengths.

Program

names is the given array of strings. We use array sort() to sort names array in ascending order based on string length.

function stringLength(str1, str2) {
    return str1.length - str2.length;
}

let names = ['Anita', 'Amy', 'America', 'Alba'];
names.sort(stringLength);
console.log(names);



copyright @2022