Array size within an object

Asked

Viewed 34 times

-2

Hello, I’m doubtful on how to count the values found inside an array, which is in an object. Thanks for your help.

 let spendin={
    recipes:[2000,5000,400],
    expenses:[8000]
}

function saldo(spendin){
    let x=0
    let limitex=spendin.recipes.length()
    let limitey=spendin.expenses.length()
    console.log(limitex)
    let somax,somay

        for(x=0;x<=limitex;x++){
            somax+=spendin.recipes[x]
        }
        for(x=0;x<=limitey;x++){
            somay+=spendin.recipes[x]
        }

    return somax-somay
} 

1 answer

1

Your question is poorly worded, but I think I’ve been able to decipher it. You want to calculate the total by adding up the taxes and subtracting the expenses, correct?

For this, the reduce method is your best friend. The Reduce method collapses an array into a value, using a function-defined logic that is passed to it. You can find more details in the MDN documentation here.

The code to calculate the total would look something like this:

const spendin = {
    recipes: [2000, 5000, 400],
    expenses: [8000],
};

const getSaldo = spendin => {
    // calcula o total da receita
    const recipesTotal = spendin.recipes.reduce((acc, item) => acc + item, 0);
    // calcula o total da despesa
    const expensesTotal = spendin.expenses.reduce((acc, item) => acc + item, 0);
    return recipesTotal - expensesTotal;
};

console.log(getSaldo(spendin));

  • It was exactly that, sorry for the confusing question, I’m starting now, I’m quite lost yet, but thank you so much for the answer

  • Don’t apologize for asking :) Seeking knowledge is always important. Good luck in your learning

Browser other questions tagged

You are not signed in. Login or sign up in order to post.