Reputation: 31
Write a function addArrays that takes 2 arrays of numbers as parameters and returns a new array where elements at same index position are added together. For example: addArrays([1,2,3], [4,3,2,1]); // => [5,5,5,1]
I am trying to use nested for loops but its giving an incorrect answers....
function addArrays(num1, num2){
var result = [];
for(var i=0; i< num1.length; i++){
for(var j=0; j<num2.length; j++){
result.push(num1[i] + num2[j]);
}
}
return result;
}
Upvotes: 2
Views: 179
Reputation: 1656
For those a little more progressive in nature...
let a = [1, 2, 3], b = [4, 3, 2, 1], l = Math.max(a.length, b.length)
const addArrays = ((a[l-1]) ? a : b).map((v, k) => (a[k] || 0) + (b[k] || 0))
console.log(addArrays) // [ 5, 5, 5, 1 ]
Upvotes: 0
Reputation: 4485
There is no need to nest with 2 loops. Nested loops for arrays are used if you have a 2 dimensional array.
function addArrays(num1, num2){
var result = [];
var size = Math.max(num1.length, num2.length);
for(var i = 0; i < size; i++){
result.push(num1[i] + (num2[i]);
}
return result;
}
You can also default it to 0 if the arrays are different lengths and you go off the end like this
(num1[i] || 0) + (num2[i] || 0)
This chooses either the number in the array, or 0 if it doesnt exist
Upvotes: 2
Reputation: 386680
I suggest to use only one loop with a check of the length and some default values if the elements do not exists.
function addArrays(array1, array2) {
var i,
l = Math.max(array1.length, array2.length),
result = [];
for (i = 0 ; i < l; i++) {
result.push((array1[i] || 0) + (array2[i] || 0));
}
return result;
}
console.log(addArrays([1, 2, 3], [4, 3, 2, 1]));
Upvotes: 4
Reputation: 1589
function addArrays(num1, num2){
var result = [];
for(var i=0; i< num1.length; i++){
result.push(num1[i] + num2[i]);
}
return result;
}
Upvotes: 0