How to sort an array based on the length of each element?
arrays, javascript, sorting, string
Solution
You can use `Array.sort` method to sort the array. The callback function should use the length of item as the sorting criteria:
// sort ascending - shorter items first
arr.sort((a, b) => a.length - b.length);
// sort descending - longer items first
arr.sort((a, b) => b.length - a.length);
You can specify additional criteria if length of two items are same:
// sort by length
// if equal then sort by dictionary order
["c", "a", "b"].sort((a, b) => a.length - b.length || a.localeCompare(b));
Problem
I have an array like this: ``` arr = [] arr[0] = "ab" arr[1] = "abcdefgh" arr[2] = "abcd" ``` After sorting, the output array should be: ``` arr[0] = "abcdefgh" arr[1] = "abcd" arr[2] = "ab" ``` I want in the `descending` order of the length of each element.