2

I need to write a function using Array.map() that takes 3 parameters: an array, a function that doubles the elements of the array and the number of times to perform the function.

For example, if I had ([1, 2, 3], double, 2) it would return [4, 8, 12].

My code so far:

const feedback = (array, func, num) => {
  return array.map(func)
}

// Helper function
function double(element) {
  return element * 2;
}

I'm struggling with how to incorporate the third parameter num. Since I need to repeat the function n number of times, I'm thinking I need a for loop? Any help would be much appreciated.

2
  • the callback function of .map() gets executed for every element in the array just saying. you would also know it if you would read just the first sentece developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… Commented Nov 3, 2020 at 6:37
  • I don't see why an additional for or while loop wouldn't work here. Just store the result of func into a variable on each iteration. Commented Nov 3, 2020 at 6:39

2 Answers 2

1

It is needed to call func for num times inside Array.map callback as follows.

const feedback = (array, func, num) => {
  return array.map((item) => {
    let val = func(item);
    for (let i = 0; i < num - 1; i ++) {
      val = func(val);
    }
    return val;
  });
}

// Helper function
function double(element) {
  return element * 2;
}

console.log(feedback([1,2,3], double, 2));

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

Comments

0

We can use the help of Array#from, Array#map and Array#reduce.

The Array#from would help in to do the operation num times (by creating a temp array) and the Array#reduce will accumulate the values after applying the operation num times into a single array:

const feedback = (array, func, num) => {
  return Array.from({length: num}).reduce(r => r.map(double), array);
}


const double = (element) => {
  return element * 2;
}

console.log(feedback([1, 2, 3], double, 0));
console.log(feedback([1, 2, 3], double, 1));
console.log(feedback([1, 2, 3], double, 2));
console.log(feedback([1, 2, 3], double, 3));
console.log(feedback([1, 2, 3], double, 4));

2 Comments

This creates so many arrays... If reduce is to be used, why not just use functional composition? Generate an array of num times the function, then compose them together into one function that applies func multiple times. jsbin.com/jefuselire/1/edit?js,console
Oops typo. That link should have been jsbin.com/duhohagase/1/edit?js,console

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.