0

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'));
mph85
  • 1,276
  • 4
  • 19
  • 39

2 Answers2

2

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); 
dwjohnston
  • 11,163
  • 32
  • 99
  • 194
0

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'));
Code Maniac
  • 37,143
  • 5
  • 39
  • 60
Sunny Goel
  • 1,982
  • 2
  • 15
  • 21