-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathproblme66.js
More file actions
34 lines (25 loc) · 1.01 KB
/
problme66.js
File metadata and controls
34 lines (25 loc) · 1.01 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
/*
Create a function that takes an array of numbers as input and returns the sum of all positive numbers in the array.
Example Input: [2, -5, 10, -3, 7] Example Output: 19 */
/* ----------------------------------
Solution One using for loop:
------------------------------------- */
function calculatePositiveNumbers(arrayOfNumbers){
let total = 0;
for( let i = 0; i < arrayOfNumbers.length; i++){
if(arrayOfNumbers[i] > 0){
total = total + arrayOfNumbers[i];
}
}
return total;
};
console.log(calculatePositiveNumbers([2, -5, 10, -3, 7]));
/* ------------------------------------------
Solution Two using es6 array method:
------------------------------------------------ */
const totalOfPositiveNumbers = arrayOfNumbers => {
const positiveNumbers = arrayOfNumbers.filter( numbers => numbers > 0);
const total = positiveNumbers.reduce((previous, present) => previous + present , 0);
return total;
}
console.log(totalOfPositiveNumbers([2, -5, 10, -3, 7]));