0

I am kind of lost on how to use the letter parameter inside the reduce function. Just doing cur.letter doesnt allow me to use it. Not sure what is causing the issue. I was able to use "letter" outside the reduce function.

The array I am using is really large in data, so I made a mock array which is similar to the array I am using.

calculateForAllLetter(arr, letter) {
  return arr.reduce(function(prev, cur) {
    return prev + parseInt(cur.letter);
  }, 0);
}
const arr = [{
  A: 10,
  B: 10,
  C: 10
}, {
  A: 10,
  B: 10,
  C: 10
}, {
  A: 10,
  B: 10,
  C: 10
}, {
  A: 10,
  B: 10,
  C: 10
}]

const totalGradesA = this.calculateForAllLetter(arr, "A")

console.log(totalGradesA)
mplungjan
  • 169,008
  • 28
  • 173
  • 236
Shalin Patel
  • 169
  • 2
  • 12
  • 2
    Please post the array you are reducing and letter in a [mcve] – mplungjan Jul 24 '20 at 18:01
  • 2
    Perhaps you need `return prev + parseInt(cur[letter]);`? But more information would make that clear. – Scott Sauyet Jul 24 '20 at 18:02
  • I made a snippet. Please fix it to be a [mcve] – mplungjan Jul 24 '20 at 18:15
  • This has nothing to do with `reduce`, you'd have the same problem accessing a dynamic property without reduce, wouldn't you? – Barmar Jul 24 '20 at 18:18
  • You can also dynamically access that variable inside some parameter destructuring, to lead to this version: `const calculateForAllLetter = (arr, letter) => arr .reduce ((total, {[letter]: ltr}) => total + ltr, 0)` – Scott Sauyet Jul 24 '20 at 18:20

2 Answers2

2

Take a look at the docs for the reduce method. You need to have a function that takes the accumulated value so far, and the current item, and then return the combination of these. As the currentItem each iteration is an object, you can use [letter] to get the contents you need.

function calculateForAllLetter(arr, letter) {
  return arr.reduce(function(accumulated, currentItem) {
    return accumulated + currentItem[letter];
  }, 0);
}

const arr = [{A: 10, B: 10, C: 10}, {A: 10, B: 10, C: 10}, {A: 10, B: 10, C: 10}, {A: 10, B: 10, C: 10}]

const totalGradesA = this.calculateForAllLetter(arr, "A")

console.log(totalGradesA)
Luke Storry
  • 6,032
  • 1
  • 9
  • 22
2
calculateForAllLetter(arr, letter){
    return arr.reduce(function(prev, cur) {
      return prev + cur[letter];
    }, 0);
  }
toto
  • 1,180
  • 2
  • 13
  • 30