How do I apply my constant array by an array the user inputs and get the sum?
The user always enters 6 digits but constant is 5 digits
Example
[5, 7, 3, 5, 2] is my constant array that I am multiplying by
user enters 837465
turns into [8, 3,7,4,6,5] (but I want 5 to be ignored)
multiply by constant array(not including last element) and get sum:
(8*5)+ (3*7) + (7*3) + (4*5)+ (6*2) = 114
const arr = [5, 7, 3, 5, 2];
var arr2 = [];
var num = parseInt(document.getElementById("yourNumber").value); //input from .html
var sum = 0;
for (var i = 1; i< num.length; i++){ //var i = 1 b/c user always enters 6 digits, i feel this is wrong?
arr2.push(parseInt(num[i]));
sum += (arr2[i]*arr[i]);
}
console.log(sum);
ishould go from0toarr.length. Make sure to check if your number has enough digits before the loop (>=arr.length). Also, you don't need to convert the value to integer, since you will be using each digit (i.e, each character) separately. Then, the operation is justsum+=arr[i]*num[i], you can access each character of a string as if it were an array.