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

206
Vistas
Javascript nested array: halve items and sum them up

I'm trying to create a function which returns me halve the data sumed up. I was able to do it on a non-nested Array but failing on the nested Array. I get the error Cannot read properties of undefined (reading 'push').

How the returned data should look like:

var data = [{"Key":1,"values":[
{"LastOnline":"21-11-29","Value":2},
{"LastOnline":"21-12-01","Value":2},
{"LastOnline":"21-12-03","Value":2}
]}];

What I have right now:

var data = [{"Key":1,"values":[
{"LastOnline":"21-11-28","Value":1},
{"LastOnline":"21-11-29","Value":1},
{"LastOnline":"21-11-30","Value":1},
{"LastOnline":"21-12-01","Value":1},
{"LastOnline":"21-12-02","Value":1},
{"LastOnline":"21-12-03","Value":1},
]}];

  function halveMonth(data){
    var newData = [];
    var temp = [{"key":data.key,"values":[{}]}];
    // sum 2 togheter
    for(var i=1;i<data.values.length;i++){
      if(data.values[i]){
        temp.values[i].push({"LastOnline":data.values[i].LastOnline, "Value":(data.values[i].Value + data.values[[i-1]].Value)});
      }
    }
    for(var i=0;i<temp.values.length;i++){
      if(i % 2 == 0){
        newData.push(temp.values[i]);
      }
    }
    return newData;
  }
  
  console.log(halveMonth(data));

about 4 years ago · Juan Pablo Isaza
3 Respuestas
Responde la pregunta

0

This works too. I basically did your idea, skipping the temp array and merging the two steps into one.

const data = [{"Key":1,"values":[
    {"LastOnline":"21-11-28","Value":1},
    {"LastOnline":"21-11-29","Value":1},
    {"LastOnline":"21-11-30","Value":1},
    {"LastOnline":"21-12-01","Value":1},
    {"LastOnline":"21-12-02","Value":1},
    {"LastOnline":"21-12-03","Value":1},
    ]}];
    
      function halveMonth(data) {
        const newData = [];
        newData.push({
            Key: data[0].Key,
            values: []
        });

        for(let i = 0; i < data[0].values.length; i++){
            if (i % 2 !== 0) {
                newData[0].values.push({
                    LastOnline: data[0].values[i].LastOnline,
                    Value: data[0].values[i].Value + data[0].values[i-1].Value
                });
            }
        }
        return newData;
      }
      
      console.log(halveMonth(data));

about 4 years ago · Juan Pablo Isaza Denunciar

0

JS variables are case sensitive. Keep the key consistent everywhere. If you don't plan to use reduce here is the solution.

var data = [{"key":1,"values":[
{"LastOnline":"21-11-28","Value":1},
{"LastOnline":"21-11-29","Value":1},
{"LastOnline":"21-11-30","Value":1},
{"LastOnline":"21-12-01","Value":1},
{"LastOnline":"21-12-02","Value":1},
{"LastOnline":"21-12-03","Value":1},
]}];

function halveMonth(data){
let newData = []
for (let i = 0; i < data.length; i++) {
    let temp = {"key":data[i].key,"values":[]}
    for (let j = 0; j < data[i].values.length; j += 2) {
        const res = (j+1===data[i].values.length) ? data[i].values[j].Value : data[i].values[j].Value + data[i].values[j+1].Value
        temp.values.push({"LastOnline":(j+1===data[i].values.length)?data[i].values[j].LastOnline:data[i].values[j+1].LastOnline,"Value":res});
    }
    newData.push(temp);
}
return newData
}
  
  console.log(halveMonth(data));

about 4 years ago · Juan Pablo Isaza Denunciar

0

First things first, you data is itself an array - so assuming your real data has more than 1 element you'll need to do the same thing for each one.

It's helpful to start off with a method which does the work on just 1 element

const justASingle = {"Key":1,"values":[{"LastOnline":"21-11-28","Value":1},{"LastOnline":"21-11-29","Value":1},{"LastOnline":"21-11-30","Value":1},{"LastOnline":"21-12-01","Value":1},{"LastOnline":"21-12-02","Value":1},{"LastOnline":"21-12-03","Value":1}]};

function halveMonthSingle(data) {

  return {
    ...data,
    values: data.values.reduce((acc, item, idx) => {
      if ((idx % 2) != 0)
        acc.push({
          ...item,
          Value: data.values[idx - 1].Value + item.Value
        })
      return acc;
    }, [])
  }
}

console.log(halveMonthSingle(justASingle))

Once you have that you can just use map do do it for every element

const data = [{"Key":1,"values":[{"LastOnline":"21-11-28","Value":1},{"LastOnline":"21-11-29","Value":1},{"LastOnline":"21-11-30","Value":1},{"LastOnline":"21-12-01","Value":1},{"LastOnline":"21-12-02","Value":1},{"LastOnline":"21-12-03","Value":1}]}];

function halveMonthSingle(data) {

  return {
    ...data,
    values: data.values.reduce((acc, item, idx) => {
      if ((idx % 2) != 0)
        acc.push({
          ...item,
          Value: data.values[idx - 1].Value + item.Value
        })
      return acc;
    }, [])
  }
}

const result = data.map(halveMonthSingle)

console.log(result)

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