Skip to content
Advertisement

javascript Sum all item in array which match same key [closed]

I have a JSON like this:

JavaScript

and i want to have an output like this:

JavaScript

the output is an array, which sum all classSize has same faculty into property totalClassSize and sum all warnedLength has same faculty into property totalWarnedLength

the input is an array and the output still an array as well

i am a beginner in learning code and i am still stuck with this problem for while

thank you so much to help me out, have a good day

Advertisement

Answer

Using Array.prototype.reduce, you can generating new object by grouping the current input array by faculty._id as object key, and based on that, you can calculate the totalWarnedLength and totalClassSize for same object keys.

JavaScript
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement