We have arrays:
[1, 2, 3, 0]
[1, 2, 3]
[1, 2]
Need to get a one array, indexes which is will be like a sum of columns. Expected result:
[3, 6, 6, 0]
We have arrays:
[1, 2, 3, 0]
[1, 2, 3]
[1, 2]
Need to get a one array, indexes which is will be like a sum of columns. Expected result:
[3, 6, 6, 0]
You can use Array.prototype.reduce() in combination with Array.prototype.forEach().
var array = [
[1, 2, 3, 0],
[1, 2, 3],
[1, 2]
],
result = array.reduce(function (r, a) {
a.forEach(function (b, i) {
r[i] = (r[i] || 0) + b;
});
return r;
}, []);
document.write('<pre>' + JSON.stringify(result, 0, 4) + '</pre>');
table.reduce(function (r, a) { r.forEach(function(b, i) { a[i] = (a[i] || 0) + b; }); return a; }, []); is not the right way.result = array.map(function (aa) { return aa.reduce(function (a, b) { return a + b; }); });function arrayColumnsSum(array) {
return array.reduce((a, b)=> // replaces two elements in array by sum of them
a.map((x, i)=> // for every `a` element returns...
x + // its value and...
(b[i] || 0) // corresponding element of `b`,
// if exists; otherwise 0
)
)
}
console.log(arrayColumnsSum([
[1, 2, 3, 0]
,[1, 2, 3]
,[1, 2]
]))
You can do something like this using map() and reduce()
// function to get sum of two array where array length of a is greater than b
function sum(a, b) {
return a.map((v, i) => v + (b[i] || 0))
}
var res = [
[1, 2, 3, 0],
[1, 2, 3],
[1, 2]
// iterate over array to reduce summed array
].reduce((a, b) => a.length > b.length ? sum(a, b) : sum(b, a))
document.write('<pre>' + JSON.stringify(res, null, 3) + '</pre>');