9

Javascript: Sort Array of Strings by Length – thisPointer.com

 3 years ago
source link: https://thispointer.com/javascript-sort-array-of-strings-by-length/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

We often use sorting while working with arrays. This article demonstrates easy ways to sort an array of strings by their length using different methods and various example illustrations. The strings within the array will be sorted based on their length. A string with the lowest length will be placed first in the array, followed by the next string with a lower length than others.

Table of Contents:

Sort an Array of Strings: Implementing sort() with compare()

Javascript’s sort() method sorts all the array elements and returns the sorted array.

The compare() function, when passed as an argument in the sort() method, defines the sorting order.

Example:-

Sort the array of strings by their length in ascending order [“George”, “Rubie”, “Veronica”, “Ed”, “Will”]

Code:-

let arrayOfStrings = ["George", "Rubie", "Veronica", "Ed", "Will"];
console.log("Before Sorting: " + arrayOfStrings );
// sort your own way by comparing lengths of elements
arrayOfStrings.sort((element1, element2) => { return element1.length - element2.length;});
console.log("After Sorting: " + arrayOfStrings);
let arrayOfStrings = ["George", "Rubie", "Veronica", "Ed", "Will"];
console.log("Before Sorting: " + arrayOfStrings );
// sort your own way by comparing lengths of elements
arrayOfStrings.sort((element1, element2) => { return element1.length - element2.length;});
console.log("After Sorting: " + arrayOfStrings);

Output:-

Before Sorting: George,Rubie,Veronica,Ed,Will
After Sorting: Ed,Will,Rubie,George,Veronica
Before Sorting: George,Rubie,Veronica,Ed,Will
After Sorting: Ed,Will,Rubie,George,Veronica

Explanation:-

  • Here, we use the sort() with compare() method passed as an argument in the above code.
  • Within the compare() function, we implement a sorting mechanism to sort the calling array based on the lengths of elements.

Sort an Array of Strings: writing custom function

In the below code, we will be implementing the Bubble Sort. Bubble sort is used to sort the elements such that adjacent elements are repeatedly swapped if they are in the wrong order. This algorithm needs one complete pass without any swap to verify if all the elements are placed in the right order

Example:-

Sort the array of strings by their length in ascending order [“George”, “Rubie”, “Veronica”, “Ed”, “Will”]

Code:-

function sortByLength(_arrayOfStrings){
//get the length of the array passed in the argument
const length = _arrayOfStrings.length;
var temp;
var newLength = length-1;
// create a sorted array
var sortedArray =_arrayOfStrings;
temp = false;
for (var i=0; i < newLength; i++)
//traverse the array and swap elements repeatedly if they are in wrong order
if (sortedArray[i].length > sortedArray[i+1].length)
var temp = sortedArray[i];
sortedArray[i] = sortedArray[i+1];
sortedArray[i+1] = temp;
temp = true;
newLength--;
} while (temp);
// return sorted array
return sortedArray;
//usage of the function
let arrayOfStrings = ["George", "Rubie", "Veronica", "Ed", "Will"];
console.log("Before Sorting: " + arrayOfStrings);
console.log("After Sorting: " + sortByLength(arrayOfStrings));
function sortByLength(_arrayOfStrings){
  //get the length of the array passed in the argument
  const length = _arrayOfStrings.length;
    var temp;
    var newLength = length-1;
    // create a sorted array
    var sortedArray =_arrayOfStrings;
    do {
        temp = false;
        for (var i=0; i < newLength; i++)
        {
          //traverse the array and swap elements repeatedly if they are in wrong order
            if (sortedArray[i].length > sortedArray[i+1].length)
            {
               var temp = sortedArray[i];
               sortedArray[i] = sortedArray[i+1];
               sortedArray[i+1] = temp;
               temp = true;
            }
        }
        newLength--;
    } while (temp);
  // return sorted array
  return sortedArray;
}
//usage of the function
let arrayOfStrings = ["George", "Rubie", "Veronica", "Ed", "Will"];
console.log("Before Sorting: " + arrayOfStrings);
console.log("After Sorting: " + sortByLength(arrayOfStrings));

Output:-

Before Sorting: George,Rubie,Veronica,Ed,Will
After Sorting: Ed,Will,Rubie,George,Veronica
Before Sorting: George,Rubie,Veronica,Ed,Will
After Sorting: Ed,Will,Rubie,George,Veronica

Explanation:-

  • Here bubble sort algorithm is usedto compare and re-arrange elements in the array based on the length of array elements.

Read More:

I hope this article helped you sort an array of strings by their length in javascript. Good Luck !!!


Recommend

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK