-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSort array by string length.js
More file actions
35 lines (26 loc) · 930 Bytes
/
Copy pathSort array by string length.js
File metadata and controls
35 lines (26 loc) · 930 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
// Write a function that takes an array of strings as an argument and returns a sorted array containing the same strings, ordered from shortest to longest.
// For example, if this array were passed as an argument:
// ["Telescopes", "Glasses", "Eyes", "Monocles"]
// Your function would return the following array:
// ["Eyes", "Glasses", "Monocles", "Telescopes"]
// All of the strings in the array passed to your function will be different lengths, so you will not have to decide how to order multiple strings of the same length.
function sortByLength(array) {
return array.sort((a, b) => a.length - b.length)
}
console.log(sortByLength(['Beg', 'Life', 'I', 'To']), [
'I',
'To',
'Beg',
'Life',
])
console.log(sortByLength(['', 'Moderately', 'Brains', 'Pizza']), [
'',
'Pizza',
'Brains',
'Moderately',
])
console.log(sortByLength(['Longer', 'Longest', 'Short']), [
'Short',
'Longer',
'Longest',
])