0
I have  an array like this having data as number values. I have to find out the sum of column values.

const data = [
    [{'data':0},{'data':3},{'data':1},{'data':0}],
    [{'data':1},{'data':1},{'data':1},{'data':1}],
    [{'data':2},{'data':2},{'data':2},{'data':2}],
    [{'data':3},{'data':3},{'data':3},{'data':3}]
];

I have to calculate the sum of records at 0 index together, 1 index together and 2 index together. Result should be calculate on the basis of column values sum.

My approach on this but it is not working alright. Giving me the different results. What is the wrong approach I am doing here.Also, I was getting result[i] as undefined so I put it in a condition with initialize empty array. But, it doesn't seems to be right logic to me.

for( let i = 0; i < data.length; i++ ) {
    let sum = 0;
    for( let j = 0; j < data[i].length; j++ ) {
    if( !result[i] ){
        result[i] = [];
    }
    sum = sum+data[i][j].data;
    result[i][j] = data[i][j];
    index++;
    }
}

Expected result on the basis of column values sum. e.g. first colum values are 0, 1,2,3 the sum will be 6.

let expectedResult = [6,9,8,6]

2 Answers 2

4

I wouldn't try to calculate the sum inside an individual iteration - instead, on each iteration, add to the associated index in the output array. There's no need for a nested result structure, all you need is a single array containing numbers.

const data = [
    [{'data':0},{'data':3},{'data':1},{'data':0}],
    [{'data':1},{'data':1},{'data':1},{'data':1}],
    [{'data':2},{'data':2},{'data':2},{'data':2}],
    [{'data':3},{'data':3},{'data':3},{'data':3}]
];

const output = [];
for (const subarr of data) {
  subarr.forEach(({ data }, i) => {
    output[i] = (output[i] || 0) + data;
  });
}
console.log(output);

Sign up to request clarification or add additional context in comments.

1 Comment

I have the data like this 16 arrays I have
3

Just iterate it properly

var data = [
    [{'data':0},{'data':3},{'data':1},{'data':0}],
    [{'data':1},{'data':1},{'data':1},{'data':1}],
    [{'data':2},{'data':2},{'data':2},{'data':2}],
    [{'data':3},{'data':3},{'data':3},{'data':3}]
];


var result = Array();

for(let i = 0; i < data[0].length; i++)
{
  for(let k = 0; k < data.length; k++)
  {
    result[i]   = result[i] || 0;
    result[i] += data[k][i].data;
  }
}

console.log(result);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.