ReactJS array reduce method example

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

The Reduce method is a method in the javascript array used to reduce the number of elements in an array.

array reduce function in javascript/typescript

Here is a syntax

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

reduce function returns only a single value from an array

For example, you have an array of numbers,

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

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

reduce function executes call back for each

React Array reduce example

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

Let’s find the sum of a mark of an object marks fields.

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

Here is an example for react reduce an array or an object into a 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>;
  }
}