Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

63
Views
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 answers
Answer question

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!