How to Sort an Array Based on the Length of Each Element in JavaScript?
Last Updated :
17 Jul, 2024
Imagine you have a list of words or groups of items, and you want to arrange them in order from shortest to longest. This is a pretty common task in JavaScript, especially when working with text or collections of things. By sorting your list in this way, you can make sense of your data and make it easier to work with or display.
Example:
Input: ["apple", "banana", "cherry", "date"]
Output: ["date", "apple", "banana", "cherry", ]
Explanation: as the date has the length 4 and apple has 5. while the banana and cherry has the same length.
but as the b comes before c so we have priorities the b that is banana rather than c that is cherry.
These are the following approaches:
Using sort() Method
The approach involves sorting a list of words by their length by the use of the sort() method. It uses a comparison function that examines the length of each word. Words are compared in pairs: if one word is shorter, it is placed before the other; if they are the same length, their order remains unchanged; if one word is longer, it is placed after the other. This results in the list being ordered from the shortest word to the longest.
Example: In this example, we use the sort() method with a custom comparator function to sort an array of strings by their length
JavaScript
const words = ["apple", "banana", "cherry", "date"];
words.sort((a, b) => a.length - b.length);
console.log(words);
Output[ 'date', 'apple', 'banana', 'cherry' ]
Using Manual Bubble Sort
The approach involves sorting an array of words by their length using the bubble sort algorithm. The algorithm repeatedly steps through the list, compares adjacent pairs of words, and swaps them if they are in the wrong order (i.e., if the first word is longer than the second). This process is repeated until the list is sorted, resulting in the words being ordered from shortest to longest.
Example: This example demonstrates how to implement a manual Bubble Sort algorithm to sort an array based on the length of its elements.
JavaScript
function bubbleSortByLength(arr) {
let len = arr.length;
for (let i = 0; i < len; i++) {
for (let j = 0; j < len - 1 - i; j++) {
if (arr[j].length > arr[j + 1].length) {
// Swap elements
[arr[j], arr[j + 1]] = [arr[j + 1], arr[j]];
}
}
}
return arr;
}
const fruits = ["kiwi", "strawberry", "grape", "orange"];
console.log(bubbleSortByLength(fruits));
Output[ 'kiwi', 'grape', 'orange', 'strawberry' ]
Conclusion
So, what did we learn today? We figured out how to put a list of things in order from shortest to longest using JavaScript. We looked at two ways to do it: a quick and easy method using a built-in tool called sort(), and a more hands-on approach using a technique called Bubble Sort. Now, you've got the skills to tidy up your lists and make them more manageable in your JavaScript projects.
Similar Reads
How to Find the Length of an Array in JavaScript ? JavaScript provides us with several approaches to count the elements within an array. The length of an array lets the developer know whether an element is present in an array or not which helps to manipulate or iterate through each element of the array to perform some operation. Table of Content Usi
3 min read
How to Sort an Array of Objects Based on a Key in JavaScript ? In JavaScript, sorting an array of objects based on the key consists of iterating over the array, applying the sort() method or other approaches, and arranging the array in the desired sorting order. Table of Content Using sort() methodUsing Custom Sorting FunctionUsing Lodash _.orderBy() MethodUsin
3 min read
How to sort an array of object by two fields in JavaScript ? We have given an array of objects and the task is to sort the array of elements by 2 fields of the object. There are two methods to solve this problem which are discussed below: Approach 1:First compare the first property, if both are unequal then sort accordingly.If they are equal then do the same
3 min read
How to Get the Size of an Array in JavaScript To get the size (or length) of an array in JavaScript, we can use array.length property. The size of array refers to the number of elements present in that array. Syntaxconst a = [ 10, 20, 30, 40, 50 ] let s = a.length; // s => 5 The JavaScript Array Length returns an unsigned integer value that
2 min read
How to Get the Longest String in an Array using JavaScript? Given an array, the task is to get the longest string from the array in JavaScript. Here are a few of the most used techniques discussed with the help of JavaScript. In this article, we will use JavaScript methods to find out the longest string in the array. All approaches are described below with e
5 min read