Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

179
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda