0

Let say I want to find the total Principal amount from across the six objects is there a way to do it quickly instead of doing it the way I am, which seem like a bad practice and would be hard to use if the number of objects are more.

Array

var monthlyInfo =[{Date: "Jan 2020", Balance: 747798, Mortgage: 2827, Principal: 2202, Interest: 625}
{Date: "Feb 2020", Balance: 745594, Mortgage: 2827, Principal: 2204, Interest: 623}
{Date: "Mar 2020", Balance: 743388, Mortgage: 2827, Principal: 2206, Interest: 621}
{Date: "Apr 2020", Balance: 741181, Mortgage: 2827, Principal: 2208, Interest: 619}
{Date: "May 2020", Balance: 738972, Mortgage: 2827, Principal: 2209, Interest: 618}
{Date: "Jun 2020", Balance: 736760, Mortgage: 2827, Principal: 2211, Interest: 616}]

Current Code

monthlyInfo[0].Principal + monthlyInfo[1].Principal + monthlyInfo[2].Principal + monthlyInfo[3].Principal + monthlyInfo[4].Principal + monthlyInfo[5].Principal 
Lim Han Yang
  • 350
  • 6
  • 23

1 Answers1

1

Just use reduce like so:

const principalTotal = monthlyInfo.reduce((a, { Principal }) => a + Principal, 0);

Snippet:

var monthlyInfo=[{Date:"Jan 2020",Balance:747798,Mortgage:2827,Principal:2202,Interest:625},{Date:"Feb 2020",Balance:745594,Mortgage:2827,Principal:2204,Interest:623},{Date:"Mar 2020",Balance:743388,Mortgage:2827,Principal:2206,Interest:621},{Date:"Apr 2020",Balance:741181,Mortgage:2827,Principal:2208,Interest:619},{Date:"May 2020",Balance:738972,Mortgage:2827,Principal:2209,Interest:618},{Date:"Jun 2020",Balance:736760,Mortgage:2827,Principal:2211,Interest:616}];

const principalTotal = monthlyInfo.reduce((a, { Principal }) => a + Principal, 0);

console.log(principalTotal);
Jack Bashford
  • 43,180
  • 11
  • 50
  • 79