return the sum of an array
Returning the Sum of an Array
If you have an array of numbers and you want to find the sum of all the numbers in the array, there are a couple of ways to accomplish this. One way is to use a for loop to iterate through the array and add up each number:
function sumArray(arr) {
var sum = 0;
for (var i = 0; i < arr.length; i++) {
sum += arr[i];
}
return sum;
}
var myArray = [1, 2, 3, 4, 5];
var mySum = sumArray(myArray);
console.log(mySum);
In this code, we define a function called sumArray
that takes an array as its argument. We then create a variable called sum
and set it to 0. We use a for loop to iterate through each number in the array and add it to the sum
variable. Finally, we return the sum
variable.
To use this function, we create an array called myArray
containing the numbers 1 through 5. We then call the sumArray
function and pass in myArray
as its argument. The result is stored in a variable called mySum
, which we then log to the console.
Another way to find the sum of an array is to use the reduce
method:
function sumArray(arr) {
var sum = arr.reduce(function(a, b) {
return a + b;
}, 0);
return sum;
}
var myArray = [1, 2, 3, 4, 5];
var mySum = sumArray(myArray);
console.log(mySum);
In this code, we define the sumArray
function again. This time, we use the reduce
method to iterate through the array and add up each number. The reduce
method takes a function as its argument that is used to accumulate the result. In this case, the function takes two arguments, a
and b
, which represent the accumulated result and the current element of the array. The function returns the sum of a
and b
. We also pass in a second argument to reduce
, which is the initial value of the accumulated result (in this case, 0). Finally, we return the result of the reduce
method.
To use this function, we create an array called myArray
containing the numbers 1 through 5. We then call the sumArray
function and pass in myArray
as its argument. The result is stored in a variable called mySum
, which we then log to the console.