Problems with Array exercise

0

I am learning in Javascript, and I am stuck in this exercise, any help please?

  

Create a script in which given two arrays of numbers, if both have the same number of elements, show an array that contains the sum of each element that is in the same position in the two arrays. Example: [1,2,3] + [2,3,4] = [3,5,7]

    
asked by Toni 22.05.2018 в 10:53
source

2 answers

1

This is an example of what you could do. Remember that you must be more explicit in what you ask and that you must show that you have at least made an effort to solve the problem.

let a = [2, 8, 8];
let b = [8, 9, 69];

function checkCorrectInput(someArray){
    // Este metodo comprueba que solo hay números en los arrays
    for(let i = 0; i < someArray.length; i++){
        let test = parseFloat(someArray[i]);
        if(isNaN(test))
            return false;
    }
    return true;
}

function sumArrays(arrayOne, arrayTwo){
    let result = [];
    if(arrayOne.length == arrayTwo.length && (checkCorrectInput(arrayOne && checkCorrectInput(arrayTwo)))){
        for(let i = 0; i < arrayOne.length; i++){
            let temp = parseFloat(arrayOne[i]) + parseFloat(arrayTwo[i]);
            result.push(temp);
        }
        return result;
    }
}

let example = sumArrays(a, b);

console.log(example);
    
answered by 23.05.2018 / 09:01
source
0
var arraysumar = new Array(1,2,3,4,5,6);

for (let i = 0; i < arraysumar.length; i++){
}   
var arraysumar2 = new Array();
for (let i = 0; i < arraysumar.length; i++){
    arraysumar2[i] = arraysumar[i];
}   
// Suma de las dos array
var resultado = new Array ();
for (let i = 0; i < arraysumar.length; i++){
        resultado[i] = arraysumar[i] + arraysumar2[i];  
}   
console.log(resultado);
    
answered by 24.05.2018 в 11:14