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]
Share
Improve this question
edited Mar 30, 2016 at 18:54
Michał Perłakowski
92.5k30 gold badges163 silver badges186 bronze badges
asked Mar 30, 2016 at 9:52
FikretFikret
2631 gold badge3 silver badges15 bronze badges
1
- Sometimes you get lucky and people don't even question the fact that you showed no efforts whatsoever. You got lucky ;) – axelduch Commented Mar 30, 2016 at 10:08
4 Answers
Reset to default 15You 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>');
Basic for loop,
var arr = [[1, 2, 3, 0],[1, 2, 3],[1, 2]];
var res = [];
for(var i=0;i<arr.length;i++){
for(var j=0;j<arr[i].length;j++){
res[j] = (res[j] || 0) + arr[i][j];
}
}
console.log(res); //[3, 6, 6, 0]
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>');