简体   繁体   中英

How to return the sum of objects-array properties instead of their double?

I was making an expense tracker basic code (without ui, only the initial script), but i had a problem while trying to console.log the sum of the total spent money by the user, my code only doubles the spent money for each bought item so i decided to ask here for help.

The code:

//initial code

const account = {
    name: 'user',
    expenses: [],
    addExpense: function(description, amount) {
        account.expenses.push({
            description: description,
            amount: amount
        });
    },
    getAccountSummary: function() {
        let expenses = account.expenses;
        for (let i = 0; i < expenses.length; i++ ) {
            let value = expenses[i].amount + expenses[i].amount;
            console.log(value);
        }
    }
}

//output calls

account.addExpense('Milk', 8);
account.addExpense('Netflix', 30);
account.addExpense('Steam summer sale', 26);
account.addExpense('Coffee', 4);
console.log(account.getAccountSummary());

The code always logs this values below:

16
60
52
8

which are actually the double of the input values (8, 30, 26, 4).

The output i'm looking for is the sum of all of those value which is in this case:

68

Hope my question was clear.

When you want a value that is based on items in an array, then you should be looking at reduce

const account = {
    name: 'user',
    expenses: [],
    addExpense: function(description, amount) {
        account.expenses.push({
            description: description,
            amount: amount
        });
    },
    getAccountSummary: function() {
       return account.expenses.reduce((acc,{amount}) => acc+amount,0);
    }
}

In your getAccountSummary

Use

let value = 0;
for (let i = 0; i < expenses.length; i++ ) {
     value += expenses[i].amount ;   
     console.log(value); 
}

Hope it will help you.

expenses[i].amount is been added 2 times at let value = expenses[i].amount + expenses[i].amount; , that's why is been doubled.

If you want to print the sum inside the getAccountSummary , you can do something like this:

  getAccountSummary: function() {
      const expenses = account.expenses;
      let value = 0
      for (let i = 0; i < expenses.length; i++ ) {
          value += expenses[i].amount;
      }
      console.log(value);
  }

But if you want to return the sum on getAccountSummary so you can print it (which seems more reasonable), then you could do this:

  getAccountSummary: function() {
      const expenses = account.expenses;
      let value = 0
      for (let i = 0; i < expenses.length; i++ ) {
          value += expenses[i].amount;
      }
      return value;
  }

And you should be able to call console.log(account.getAccountSummary());

You can use forEach() to iterate over expenses as well.

The main issue was that you were logging the values directly, instead of returning them for later logging.

Also, there's no need to use the "function" keyword in modern Javascript.

Here's my solution, gives the expected output.

const account = {

    name: 'user',
    expenses: [],

    addExpense(description, amount) {
        account.expenses.push({
            description: description,
            amount: amount
        });
    },

    getAccountSummary() {

        return account.expenses.reduce((result, expense) => result + expense.amount, 0)
    }
}

//output calls

account.addExpense('Milk', 8);
account.addExpense('Netflix', 30);
account.addExpense('Steam summer sale', 26);
account.addExpense('Coffee', 4);
console.log(account.getAccountSummary()); // 68

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM