JavaScript Code

How to sort array of strings based on string length?


Problem Statement

given an array of strings, 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