Reputation: 1356
How would I rewrite this using an arrow function?
Would forEach
be the only way?
And what would be an example of an arrow function that doesn't use
the forEach
method.
CODE
let word = 'Bloc';
const reverseString = (str) => {
let stack = [];
for (let i of str) {
stack.push(str[i]);
}
let reversed = '';
for (let i of word) {
reversed += stack.pop();
}
return reversed;
}
console.log(reverseString('Bloc'));
Upvotes: 0
Views: 334
Reputation: 2142
In this case for reverse String you can also follow the following code :-
let word = 'Bloc';
const reverseString = (str) => {
let reversed = '';
// use split function of string to split and get array of letter and then call the reverse method of array and then join it .
reversed = str.split('').reverse().join('');
return reversed;
}
console.log(reverseString('Bloc'));
Upvotes: 0
Reputation: 11880
You would use the Array.reduce method. (In this case, reduceRight).
const str = 'helloworld';
const newStr = str.split('').reduceRight((acc, cur) => {
return acc + cur;
}, '');
console.log(newStr);
Upvotes: 2