Sum of Array
Write a function that finds the sum of all elements in an array.
Advanced
Instructions
Write a function that receives an array of numbers and returns the sum of all elements in it.
For example, if the input is [1,10,20], the output should be 31.
Tests
0/7
Function Call:
Expected:
sumArray([1,10,20])
31
Run test
sumArray([-5, -2, 0])
-7
Run test
sumArray([])
0
Run test
Hidden Test
?
Run test
Hidden Test
?
Run test
Hidden Test
?
Run test
Hidden Test
?
Run test
See Solution
Solution
const sumArray = (myArray) => {
return myArray.reduce((acc, current) => acc + current, 0)
}
Explanation
The operation is simple. We loop through the numbers from 1 to 100 and check if the number is divisible by 3, 5 or both. If it is divisible by 3, we print "Fizz", if it is divisible by 5, we print "Buzz" and if it is divisible by both 3 and 5, we print "FizzBuzz". If none of the conditions are met, we print the number itself.
Complexity Analysis
The time complexity for this algorithm is O(n) where n is the value given to the function.
Alternative
Recursive
const sumArray = (myArray) => {
let result = 0
for(const i of myArray){
result += i
}
return result
}
Any improvement idea? Share with us!