DEV Community

Cover image for Reduce method to sum values of array of objects
ShubhamTiwari909
ShubhamTiwari909

Posted on

Reduce method to sum values of array of objects

Hello guys today i am going to show you how to use reduce method to sum up the values of array of objects.

Reduce method -
The reduce() method executes a user-supplied “reducer” callback function on each element of the array, passing in the return value from the calculation on the preceding element. The final result of running the reducer across all elements of the array is a single value.

Perhaps the easiest-to-understand case for reduce() is to return the sum of all the elements in an array.

Here is an example of reduce method

import React from 'react'

function App() {

    const data  = [
        {
            Name : "shubham",
            Marks:100
        },
        {
            Name : "bharat",
            Marks:90
        },
        {
            Name : "abhishek",
            Marks:80
        },
        {
            Name : "himanshu",
            Marks:90
        },
        {
            Name : "alfiya",
            Marks:68
        },
        {
            Name : "akshay",
            Marks:79
        }
    ];

    var total = data.reduce((accum,item) => accum + item.Marks, 0)

    return (
        <div>
            {data.map((item) => (
                <div className="m-5" style={{display:"grid",gridTemplateColumns:"repeat(2,1fr)",justifyContent:"center"}}>
                    <p>{item.Name}</p>
                    <p>{item.Marks}</p>
                </div>
            ))}
            <div className="m-5" style={{display:"grid",gridTemplateColumns:"repeat(2,1fr)",justifyContent:"center"}}>
                <p></p>
                <p className="my-5">{total}</p>
            </div>


        </div>
    )
}

export default App
Enter fullscreen mode Exit fullscreen mode

Working -

  1. First we define an array of objects named "data".
  2. Then We stored the reduce method in a variable named "total".
  3. Then inside reduce method , we have two parameters named "accum" which stands for accumulator and "item" which is the value we need to sum up.
  4. accum is started with 0 and then add the Marks of each object item one by one and sum up all the values and return the final result , which is sum of all the values which is passed to the reduce function.
  5. Then finally we have mapped the data using map() method and below it we have put the total in a

    tag which shows the total value on the webpage.

Screenshot (32)

NOTE- this is just a demo of reduce() method so, there is not much styling in the webpage!!

I hope you understand the concept and if there is any mistake or suggestion then please mention it in the comment section.

THANK YOU FOR READING THIS POST.

Discussion (0)