ReactJS array reduce method example

In this tutorials, You will learn array reduce method in javascript/typescript, an example for how to reduce array of objects into single value in react application

Reduce method is a method in javascript array used to reduce number of elements in array

array reduce function in javascript/typescript

Here is an syntax

array.reduce(function(accumalator, currentValue, currentIndex, array), initialValue)

reduce function returns only single value from an array

For example you have an array of numbers,

let ’s find how You can sum this array values using array reduce function

const numberArray = [3,1,8,0,10,20];
const total = numberArray.reduce(
(previousValue, currentValue, index)=>previousValue+currentValue, 

reduce function executes call back for each

React Array reduce example

In this example, We have an array of object, Each object contains id and marks.

Let’s find the sum of an marks of an object marks fields

  • Declared array of objects in array
  • Reduce iterates an array and apply this method, This will iterates single value
  • reduce has an callback which accepts previous value and current value
  • returns the sum of previous and current value

Here is an example for react reduce array of object into single value

import React from "react";
import "./style.css";

export default class App extends React.Component {
  students = [
      id: "11",
      marks: 31
      id: "12",
      marks: 80
      id: "3",
      marks: 98
  render() {
    let total = this.students.reduce(function(prev, current) {
      return prev + +current.marks;
    }, 0);

    return <h1>Total Marks, {total}</h1>;

Join 6,000 subscribers and get a daily digest of full stack tutorials delivered to your inbox directly.No spam ever. Unsubscribe any time.

Similar Posts
You'll get a notification every time a post gets published here.