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'));
5
  • 2
    You are already using an arrow function in your code, and you are using no functions. There are no non-arrow functions to convert to arrow functions. Commented Jun 6, 2019 at 6:59
  • Might belong to CodeReivew but...what do you want to re-write here? Commented Jun 6, 2019 at 7:01
  • converting the for loops into arrow functions Commented Jun 6, 2019 at 7:02
  • 1
    But that doesn't mean anything. Commented Jun 6, 2019 at 7:02
  • Possible duplicate of Loop through an array in JavaScript Commented Jun 6, 2019 at 7:09

2 Answers 2

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); 

Sign up to request clarification or add additional context in comments.

Comments

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'));

1 Comment

This doesn't really answer the question - which is about how to avoid using for loops.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.