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

205
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório

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 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