2

Sorry this is basic things but I dont know java-script array

I have simple array with same number of index and n number of array, If index have no value it will be null

Array [
        0: Array [ null, 10222, 10222, null,9999 ]
        1: Array [ 1870963, 1845801, 1830263, null, null ]
        2: Array [ 1870963, 1845801, 1830263, null, null ]
        n: Array [ n, n, n, n, n ]
    ];

So I need to make in in single array with sum just like below.

Array [3741926,3701824,3670748,0,9999];

Just need to make sum and into single array.

4 Answers 4

3

Iterate the array with Array#map, and sum each column using Array#reduce:

var arr = [
  [null, 10222, 10222, null, 9999],
  [1870963, 1845801, 1830263, null, null],
  [1870963, 1845801, 1830263, null, null],
];

var result = arr[0].map(function(a, i) {
  return arr.reduce(function(s, n) {
    return s + n[i];
  }, 0);
});

console.log(result);

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

Comments

2

You can use reduce like so:

const a = [
        [ null, 10222, 10222, null,9999 ],
        [ 1870963, 1845801, 1830263, null, null ],
        [ 1870963, 1845801, 1830263, null, null ]
    ];
    
console.log(a.reduce((acc, cur) => acc.map((x, i) => x + cur[i])))

Comments

1

You can use array.prototype.map and array.prototype.reduce:

var arr = [
  [ null, 10222, 10222, null,9999 ],
  [ 1870963, 1845801, 1830263, null, null ],
  [ 1870963, 1845801, 1830263, null, null ]
];

var result = arr[0].map((_, i) => arr.reduce((m, e) => m + e[i], 0));

console.log(result);

4 Comments

Look at the output the OP wants. It's the sum of each array's n index.
@AnkitSoni I've fixed
Your row variable in map() method is misleading. It won't keep "row", but the element from first array.
@EganWolf Fixed
0

You can use array#reduce with array#foreach.

var arr = [ [ null, 10222, 10222, null,9999 ],[ 1870963, 1845801, 1830263, null, null ],[ 1870963, 1845801, 1830263, null, null ],[ null, null, null, null, null ]];
var result = arr.reduce((r,a,j) => {
  a.forEach((v,i) => {
    r[i] = (r[i]||0) + (v||0); 
  });
  return r;
},[]);

console.log(result);

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.