Handling Objects With Javascript Reduce

Viewed 33

This is my object:

let data = [
        {acnumber: 1, acname: "Mr X", acterm: "shorterm", acbalance: 150},
        {acnumber: 2, acname: "Mr Y", acterm: "longterm", acbalance: 140},
        {acnumber: 3, acname: "Mr Z", acterm: "shorterm", acbalance: 155}
    ]

Because I need information about number of accounts and account balance for 'shortterm' loans only, I can filter this data this way:

let shortTerm = data.filter((item)=>{
        if (item.acterm === "shorterm") {
            return item;
        }
    })

Then I can find number of shortterm loan accounts using this:

let numberOfAccounts = shortTerm.length;

Also, I can find sum of account balance using this:

let accountBalance = shortTerm.reduce((acc, item)=>{
        return acc+item.acbalance;
    },0)

I was wondering if there is any better or more precise ways of getting the same result. I will highly appreciate any assistance.

1 Answers

A single .reduce will work - add the property to the accumulator only if the object being iterated over is shortterm. Use concise return if you want.

let data = [
        {acnumber: 1, acname: "Mr X", acterm: "shorterm", acbalance: 150},
        {acnumber: 2, acname: "Mr Y", acterm: "longterm", acbalance: 140},
        {acnumber: 3, acname: "Mr Z", acterm: "shorterm", acbalance: 155}
    ]
const balance = data.reduce(
  (a, obj) => a + (obj.acterm === 'shorterm' ? obj.acbalance : 0),
  0
);
console.log(balance);

Related