Jon Nicholson
Jon Nicholson

Reputation: 1141

Reduce function returning NaN when pulling object from array - MongoDB database, React frontend

I have the following Schema:

const SubmitDebtSchema = new Schema ({
  balance: [{
    balanceDate: Date,
    newBalance: Number
  }],
});

I am attempting to loop through my database entries, pull the 'newBalance' out from each object in the balance array, and then reduce / sum them together.

However, it is returning 'NaN' - and I can't figure out why.

Here is my Axios call to get the data:

  componentDidMount() {

    axios.get("/api/fetch/fetchDebtCards")
    .then((response) => {
      this.setState({
        debts: response.data
      })
      console.log(this.state.debts.balance.newBalance)
    })
  }

The console log in there successfully retrieves the database entries.

And here is my reduce function:

const sumBalance = this.state.debts.reduce(function(previousValue, currentValue) {
          return (
            previousValue + currentValue.balance.newBalance
          )
        }, 0)

You can see, I'm attempting to tap into 'balance.newBalance' to access the newBalance within each of the balance objects.

Can anyone point out what I'm doing wrong?

EDIT: My console log, with two entries. What I want to do is get the newBalance array.length -1 from these, and sum them together by reducing.

[Log] Array

0 Object

balance: [{_id: "5fbbddd1077c56000828973c", balanceDate: "2020-11-23T16:05:36.124Z", newBalance: 400}]

1 Object

balance: [{_id: "5fbc06f58b2f98000865df54", balanceDate: "2020-11-23T19:01:07.789Z", newBalance: 300}] (1)

Upvotes: 0

Views: 121

Answers (1)

Elvis
Elvis

Reputation: 1143

if "console.log(this.state.debts.balance.newBalance)" works then debts is not an array, how are you using map on debts then? Map can only be used on arrays.

I'm not sure how your debts object/array is exactly. Maybe a log of it would be helpful.

If it is an array, then this might work.

const sumBalance = this.state.debts.map(x => x.balance).flat().reduce((a,b) => a + b.newBalance, 0)

whereas if it's an object, then this might work

const sumBalance = this.state.debts.balance.reduce((a,b) => a+b.newBalance, 0)

If none of these work, just log "this.state.debts" and let us see what you have there.

Edit: Ok so you only need the last values of the balance arrays (the latest balance), something like this?

const sumBalance = this.state.debts.map(x => x.balance[x.balance.length-1].newBalance).reduce((a,b) => a + b, 0)

Upvotes: 1

Related Questions