|
3 | 3 | * CODERBYTE BEGINNER CHALLENGE *
|
4 | 4 | * *
|
5 | 5 | * Alphabet Soup *
|
6 |
| -* Using the JavaScript language, have the function FirstFactorial(num) take the num * |
7 |
| -* parameter being passed and return the factorial of it (ie. if num = 4, * |
8 |
| -* return (4 * 3 * 2 * 1)). For the test cases, the range will be between 1 and 18. * * |
| 6 | +* Have the function AlphabetSoup(str) take the str string parameter being passed * |
| 7 | +* and return the string with the letters in alphabetical order * |
| 8 | +* (ie. hello becomes ehllo). Assume numbers and punctuation symbols will not be * |
| 9 | +* included in the string. * |
9 | 10 | * *
|
10 | 11 | * SOLUTION *
|
11 |
| -* You can either use an iterative or recursive function to solve this challenge. * |
12 |
| -* I am going to use an interative function. I am going to start with a value of 1 * |
13 |
| -* for my total and then keep multiplying it by the next number until I reach num. * |
14 |
| -* * |
15 |
| -* This function needs to account for a possible outlier - One and Zero. * |
16 |
| -* If num is 1 or 0 then the answer is 1. By setting tot to value of 1 at * |
17 |
| -* initialization, then it guaranteees that 1 will be returned if num is ever 0 or 1. * |
| 12 | +* The Array has a built-in sort function but String does not. The first step is to * |
| 13 | +* convert the string to an Array and sort it in alphabetical order. Then covert the * |
| 14 | +* Array back to a string with the toString() function. The last step is to remove * |
| 15 | +* the commans that separate each character. * |
18 | 16 | * Steps for solution *
|
19 |
| -* 1) Set var tot to 1. * |
20 |
| -* 2) Loop from 2 to num and multiple tot by num to get new tot. * |
21 |
| -* 3) Return tot for answer. * |
| 17 | +* 1) Convert string to an array * |
| 18 | +* 2) Sort array in alphabetical order * |
| 19 | +* 3) Convert array back to a string * |
| 20 | +* 4) Remove comma separators in our string * |
22 | 21 | * *
|
23 | 22 | ***************************************************************************************/
|
24 | 23 |
|
25 | 24 | function AlphabetSoup(str) {
|
26 | 25 |
|
27 |
| - return str.split("").sort().join(""); |
| 26 | + var myArray = str.split("") |
| 27 | + |
| 28 | + myArray.sort(); |
| 29 | + var newStr = myArray.toString(); |
| 30 | + |
| 31 | + return newStr.replace(/,/g, ""); |
28 | 32 |
|
29 | 33 | }
|
0 commit comments