sort an array by characters length in js

Sorting an Array by Character Length in JavaScript

Sorting an array by character length is a common task in JavaScript. There are several ways to achieve this, but the most efficient way is to use the built-in sort() method.

Method 1: Using the sort() Method

The sort() method sorts the elements of an array in place and returns the sorted array. We can use this method to sort an array by character length by passing a custom comparison function as a parameter to the sort() method.


const arr = ["apple", "banana", "cherry", "date", "eggs"];
arr.sort((a, b) => a.length - b.length);
console.log(arr); // Output: ["date", "eggs", "apple", "banana", "cherry"]

In the above example, we have defined an array of strings and passed a comparison function to the sort() method. The comparison function compares the length of two strings and returns a negative value if the first string is shorter than the second string, a positive value if the first string is longer than the second string, and zero if both strings have equal length.

Method 2: Using the map() Method

We can also sort an array by character length using the map(), sort(), and reduce() methods.


const arr = ["apple", "banana", "cherry", "date", "eggs"];
const sortedArr = arr.map((elem) => elem).sort((a, b) => a.length - b.length);
console.log(sortedArr); // Output: ["date", "eggs", "apple", "banana", "cherry"]

In the above example, we have used the map() method to copy the elements of the original array to a new array. Then, we have used the sort() method to sort the new array by character length. Finally, we have returned the sorted array using the reduce() method.

Method 3: Using the Spread Operator and the sort() Method

We can also sort an array by character length using the spread operator and the sort() method.


const arr = ["apple", "banana", "cherry", "date", "eggs"];
const sortedArr = [...arr].sort((a, b) => a.length - b.length);
console.log(sortedArr); // Output: ["date", "eggs", "apple", "banana", "cherry"]

In the above example, we have used the spread operator to copy the elements of the original array to a new array. Then, we have used the sort() method to sort the new array by character length.

Conclusion

Sorting an array by character length in JavaScript is a simple task that can be achieved using several methods. The most efficient way is to use the built-in sort() method with a custom comparison function.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe