The reverse
method flips the order of the elements within an array.
However, reverse
does not affect the digits or characters within those
elements.
Example
1let arr = ['hello', 'world', 123, 'orange'];
2
3arr.reverse()
4console.log(arr);
Console Output
['orange', 123, 'world', 'hello']
What if we wanted the reversed array to be
['egnaro', 321, 'dlrow', 'olleh']
?
Let's have some fun by creating a process that reverses BOTH the order of the entries in an array AND the order of characters within the individual elements.
Remember that a function should perform only one task. To follow this best practice, we will solve the array reversal by defining two functions - one that reverses the characters in a string (or the digits in a number) and one that flips the order of entries in the array.
split
and join
methods. Let's rebuild that function now.reverseCharacters
. Give it one parameter, which will
be the string to reverse.split
the string into an array, then reverse the
array.join
to create the reversed string and return that string from the
function.console.log(reverseCharacters(myVariableName));
to call the function and verify
that it correctly reverses the characters in the string.Code exercises 1 - 3 at repl.it
Tip
Use these sample strings for testing:
'apple'
'LC101'
'Capitalized Letters'
'I love the smell of code in the morning.'
reverseCharacters
function works great on strings, but what if the
argument passed to the function is a number? Using
console.log(reverseCharacters(1234));
results in an error, since
split
only works on strings (TRY IT). When passed a number, we want the
function to return a number with all the digits reversed (e.g. 1234 converts
to 4321 and NOT the string "4321"
).if
statement to reverseCharacters
to check the typeof
the
parameter.typeof
is 'string', return the reversed string as before.typeof
is 'number', convert the parameter to a string, reverse the
characters, then convert it back into a number.Tip
Use these samples for testing:
1234
'LC101'
8675309
'radar'
reverseCharacters
to flip the
characters or digits.Tip
Use this sample data for testing.
Input | Output |
---|---|
['apple', 'potato', 'Capitalized Words'] |
['sdroW dezilatipaC', 'otatop', 'elppa'] |
[123, 8897, 42, 1138, 8675309] |
[9035768, 8311, 24, 7988, 321] |
['hello', 'world', 123, 'orange'] |
['egnaro', 321, 'dlrow', 'olleh'] |
funPhrase
.We put the '___' in '___'.
Fill the first blank with the modified string, and fill the second blank
with the original string.str
and initialize it
with a string (e.g. 'Functions rock!'
).Tip
Use these test cases.