-1

Can anyone explain in detail how this piece of code works?

const yourAmazingFunction = (salaries) => Object.values(salaries).reduce((acc, el) => acc + el, 0);

specifically this:

((acc, el) => acc + el, 0);

Here's all the code:

const nonEmptySalaries = {
 John: 100,
 Ann: 160,
 Pete: 130
};

const emptySalaries = {};

const yourAmazingFunction = (salaries) => Object.values(salaries).reduce((acc, el) => acc + el, 0);

const firstResult = yourAmazingFunction(nonEmptySalaries)

const secondResult = yourAmazingFunction(emptySalaries)

console.log(firstResult); // 390
console.log(secondResult); // 0 ```

Nik_K
  • 3
  • 1
  • 2
    Does this help: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce – gen_Eric Jun 24 '21 at 21:32
  • 2
    @RocketHazmat event better link: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce#sum_all_the_values_of_an_array – VLAZ Jun 24 '21 at 21:33
  • Does this answer your question? [How to sum the values of a JavaScript object?](https://stackoverflow.com/questions/16449295/how-to-sum-the-values-of-a-javascript-object) – Ivar Jun 24 '21 at 21:37
  • I have already looked through these resources, but there were still some questions. In any case, the problem has already been resolved, thanks for the advice. – Nik_K Jun 24 '21 at 21:50
  • Why close this? This question seems OK as is. – 0xLogN Jun 24 '21 at 22:13

1 Answers1

0
  1. Take all of the values (in this case an array [100, 160, 130])
  2. Loop over the array values, setting acc to the result of the last call of the callback, or 0 if this is the first call, and el to the current element. Basically add together each number (callback(0, 100) then callback(100, 160) then callback(260, 130) to return 390).
0xLogN
  • 3,289
  • 1
  • 14
  • 35