Home > Software design >  How to use reduce method within map method to add numbers
How to use reduce method within map method to add numbers

Time:05-24

Not sure if I am overcomplicating things but I am trying to get the sum of all the numbers inside this array of arrays:

const frames = [
  [2, 0], [4, 2], [6, 0], [2, 4], [1, 5], [7, 0], [5, 2], [7, 0], [2, 6], [8, 1]
]

I am practising using map and reduce to do so:

const score = (frames) =>{
  console.log(frames)
  let addedScores = frames.map(frame.reduce((previousValue, currentValue) => previousValue   currentValue))
  console.log(addedScores)
}

But currently getting this error:

TypeError: 2,04,26,02,41,57,05,27,02,68,1 is not a function
    at Array.map (<anonymous>)
    at score (/Users/x/Desktop/Programming/devacademy/bootcamp/week1/preparation/bowling-kata/game.js:8:28)
    at Object.<anonymous> (/Users/x/Desktop/Programming/devacademy/bootcamp/week1/preparation/bowling-kata/game.js:17:1)

Here is a fiddle version.

Any advice and explanation would be greatly appreciated

CodePudding user response:

You are almost there on this one! If you look at the stack trace for the error you are facing, you will see that an error is thrown by Array.map function, and namely that "stuff" (i.e 2,04,26,02,41,57,05,27,02,68,1) is "not a function".

The map higher-order function expects a function that it will map accross the elements of frames.

What you want is something like this:


//...
  let addedScores = frames.map((frame) => frame.reduce((previousValue, currentValue) => previousValue   currentValue))
//...


Here I have only converted your addedScores expression to pass an anonymous function: (frame) => { ... } to the map function.

Hope this helps!

The resulting shape for addedScores would be: [2, 6, 6, 6, 6, 7, ...], which is the sum of each pair of numbers in frames.

  • Related