Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

169
Visualizações
Taking array values and adding the results - getting NaN

I am working with an array that I am trying to get the total sum per day and then return an array with such results. My approach so far is incorrect as I am getting NaN after applying sum. I am at a dead end and unsure why. I am able to apply a similar logic if I wanted to get the total sum of all days but this doesnt work for the sum of each day. What would be the right approach to achieve the below output?

Array

var test = [{ statistics: [{
   "date": "03-13-2022",
   "balance": 19.88,
},
{
   "date": "03-13-2022",
   "balance": 12.99,
},
{
   "date": "03-14-2022",
   "balance": 17.97,
},
{
   "date": "03-14-2022",
   "balance": 19.64,
}]}];

Currently this is returning NaN for the sum:

let balance = [];
for (let s = 0; s < test[0].statistics.length; s++) {
   console.log(test[0].statistics[s].date);
   balance[`${test[0].statistics[s].date}`] += test[0].statistics[s].balance;
}
//Returns : 
//[ '03-13-2022': NaN, '03-14-2022': NaN ]

This returns the total sum :/. I want the total sum per day

let balance2 = 0;
for (let s = 0; s < test[0].statistics.length; s++) {
   console.log(test[0].statistics[s].date);
   balance2 += test[0].statistics[s].balance2;
}
//70.48

Desired Outcome:

[
   {
      date: '03-13-2022',
      balance: 32.87
   },
   {
      date: '03-14-2022',
      balance: 37.61
   }   
]
about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

You need to set default value 0 for balance[test[0].statistics[s].date] if it's undefined.

Because an undefined value + a number = NaN

if (!balance[test[0].statistics[s].date]) {
    balance[test[0].statistics[s].date] = 0
}

var test = [{
  statistics: [{
      "date": "03-13-2022",
      "balance": 19.88,
    },
    {
      "date": "03-13-2022",
      "balance": 12.99,
    },
    {
      "date": "03-14-2022",
      "balance": 17.97,
    },
    {
      "date": "03-14-2022",
      "balance": 19.64,
    }
  ]
}];

let balance = {};
for (let s = 0; s < test[0].statistics.length; s++) {
  if (!balance[test[0].statistics[s].date]) {
    balance[test[0].statistics[s].date] = 0
  }
  balance[test[0].statistics[s].date] += test[0].statistics[s].balance;
}

console.log(balance)

about 4 years ago · Juan Pablo Isaza Relatório

0

Here are my codes returning the same as the desired outcome,

var test = [{ statistics: [{
   "date": "03-13-2022",
   "balance": 19.88,
},
{
   "date": "03-13-2022",
   "balance": 12.99,
},
{
   "date": "03-14-2022",
   "balance": 17.97,
},
{
   "date": "03-14-2022",
   "balance": 19.64,
}]}];

// Grouping all data according to respective dates
const returnGroupedData = (arr)=>{
const data = {};
    arr.forEach((ar) => {
        data[ar.date] =  [...(data[ar.date] || []), {date: ar.date, balance: ar.balance}]
    });
  return data;
};

//Returning the sum
const returnTheSum =(obj)=>{
  return Object.keys(obj).map(item=>{
    let balances = [...obj[item].map(arr=>arr.balance)]
    let sum = balances.reduce((total, num)=>{
      return total + num
    })
    return {date: item, balance: sum}
  })
}

console.log(returnTheSum(returnGroupedData(test[0].statistics)));
about 4 years ago · Juan Pablo Isaza Relatório

0

You can use Array#reduce() especially if you have balances for multiple dates in which the output is an object with the dates as the keys and total balances as the values.

const test = [{ statistics: [{"date": "03-13-2022","balance": 19.88},{"date": "03-13-2022","balance": 12.99},{"date": "03-14-2022","balance": 17.97},{"date": "03-14-2022","balance": 19.64},{"date": "03-14-2022","balance": 29.88},{"date": "03-14-2022","balance": 6.99},{"date": "03-15-2022","balance": 1.97},{"date": "03-15-2022","balance": 39.64}]}];

const totals = test[0].statistics.reduce(
    (prev, {date,balance}) =>
    ({...prev,[date]:(prev[date] || 0) + balance}), {}
);

console.log( totals );
/* OUTPUT
{
  "03-13-2022": 32.87,
  "03-14-2022": 74.47999999999999,
  "03-15-2022": 41.61
}
*/

//To convert to your desired output use:
const desired = Object.entries( totals ).map( ([date,balance]) => ({date,balance}) );
console.log( desired );
/* OUTPUT
[
  {
    "date": "03-13-2022",
    "balance": 32.87
  },
  {
    "date": "03-14-2022",
    "balance": 74.47999999999999
  },
  {
    "date": "03-15-2022",
    "balance": 41.61
  }
]
*/

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda