0

I'm trying to pass this deepMap([4,5, [3,4,[2]]], x => x + 5) into this function:

const deepMap = (arr, fn) => {
  return arr.reduce((first, second) => first.concat(Array.isArray(second) ? [deepMap(second)] : fn), []);  
}

previously it worked like this:

const deepMap = (arr, fn) => {
  return arr.reduce((first, second) => first.concat(Array.isArray(second) ? [deepMap(second)] : second + 5), []);  
}

but that didn't allow me to use the function in the second parameter. I know it needs to work like the second example, but the only way I can think to change it is like it is in the first example. I have tried numerous variations experimentally but I keep getting an error or the wrong answer.

4
  • Array.concat expects an array - [second + 5]? Commented Jun 1, 2017 at 20:00
  • Inside the deepMap function the function passed as an argument is named fn, so you call it like fn(xyz). If you want subsequent recursive calls to deepMap to also be able to call it, you have to pass it on: deepMap(second, fn). Commented Jun 1, 2017 at 20:00
  • Are you getting any errors? Commented Jun 1, 2017 at 20:00
  • adding fn to the call deepMap definitely helped. Thank You so much!!!! Commented Jun 1, 2017 at 20:04

2 Answers 2

1

You should put return value of function instead of function itself. Like this:

const deepMap = (arr, fn) => {
  return arr.reduce((first, second) => first.concat(Array.isArray(second) ? [deepMap(second, fn)] : fn(second)), []);  
}
Sign up to request clarification or add additional context in comments.

2 Comments

Your code doesn't work. Inner deepMap should be called like deepMap(second, fn), not deepMap(second)
Ok, fixed, Thanks wostex
0

Just pass both array and function to recursive deepMap calls and invoke fn(cur) instead of just pointing to it.

const deepMap = (arr, fn) => {
  return arr.reduce((first, second) => first.concat(Array.isArray(second) ? [deepMap(second, fn)] : fn(second)), []);  
}

const res = deepMap([4,5, [3,4,[2]]], x => x + 5);

console.log(res)

2 Comments

No explanation is not helpful
@mhodges I've added it while you were writing this comment.

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.