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

64
Visualizações
JavaSript Sum data

Hi guys after doing various transformations I have this array of objects:

I need a dynamic function that allows me to create the following object, where data[i] will be the sum of data[i] values ​​of the object above.

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

because you use angular, you can transform your data response in a class/interface. Your entire json is a list of "Items"

export interface Item {
  name: string,
  data: number[]
}

// let rows: Item[] = your_json

then, you can create your totalItem as:

assuming all your data array have same length:

const rowValues = rows.map(x => x.data);

// using first row of your array, you can map results for each column of your matrix (rowValues is a matrix), 
// then, iterating each row, you add the sum of specified column index
const values = rowValues[0].map((x, i) => {
  let sum = 0;
  rowValues.forEach(r => sum += r[i]);
  return sum;
});

const totalObj = {
  name: 'Total',
  data: values
};

Is not the best solution, but I think is working

about 4 years ago · Juan Pablo Isaza Relatório

0

Here is a solution for your problem within two looping structure

let rowData = [
  {
    "name": "TEST1",
    "data": [
      1,
      2
    ]
  },
  {
    "name": "TEST2",
    "data": [
      1,
      2
    ]
  },
  {
    "name": "TEST3",
    "data": [
      1,
      2
    ]
  }
]


var result = Array(rowData.length ? rowData[0].data.length : 0).fill(0)
rowData.map(ele=>ele.data?.map((e,idx)=>result[idx]+=e || 0))
var output = {"name":"Total","data":result};
console.log(output)

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