简体   繁体   中英

reduce function in JavaScript and the accumulator object

I have a query in relation to the reduce function.

The code is as follows:

const marks = [60, 55, 80, 89, 90, 98, 75, 72, 50, 30, 20, 42]
const grade_count = marks.reduce(groupByGrade, {})
function groupByGrade (acc, mark) {
  
  const {a = 0, b = 0, c = 0, d = 0, f = 0} = acc;
  if (mark >= 90) {
    return {...acc, a: a + 1};
  }
  if (mark >= 80) {
    return {...acc, b: b + 1};
  }
  if (mark >= 70) {
    return {...acc, c: c + 1};
  }
  if (mark >= 60) {
    return {...acc, d: d + 1};
  }
  else {
    return {...acc, f: f + 1};
  }
}
 
console.log (marks)
console.log (grade_count)
console.log ('woo hoo')

My query is in relation to the following line where the accumulator is destructured for the first time:

const {a = 0, b = 0, c = 0, d = 0, f = 0} = acc;

I wish to understand how come the properties on the accumulator object not get reset to zero on every iteration of the marks array.

What am I missing here please?

I wish to understand how come the properties on the accumulator object not get reset to zero on every iteration of the marks array.

Because the = 0 part of

const {a = 0, b = 0, c = 0, d = 0, f = 0} = acc;

...is only used if the effective value of the property being destructured is undefined ("effective" = it's actually undefined , or the property's not there at all).

On subsequent calls to the reducer, acc has non- undefined values for those properties, so the default isn't used.


Just as a side note, you could do the destructuring in the parameter list:

function groupByGrade({a = 0, b = 0, c = 0, d = 0, f = 0}, mark) {
    // ...
}

...although a , b , and the others wouldn't be constants anymore.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM