Use a nested array, and loop over the array rather than hard-coding two array variables.
You can use arrays.map()
to get all the lengths so you can calculate the maximum length. And arrays.reduce()
to sum up an element in each array.
const addTogether = (...arrays) => {
let result = [];
let len = Math.max(...arrays.map(a => a.length));
for (let i = 0; i < len; i++) {
result.push(arrays.reduce((sum, arr) => sum + (arr[i] || 0), 0));
}
return result
}
console.log(addTogether([1, 2, 3], [4, 5], [6]));
CLICK HERE to find out more related problems solutions.