Skip to content

Commit b152ffb

Browse files
author
wakidurrahman
committed
feat: oddBallSumVariationReduce
1 parent 29686a8 commit b152ffb

File tree

1 file changed

+38
-0
lines changed

1 file changed

+38
-0
lines changed

src/code-challenges/code-challenges-003-010.js

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -68,3 +68,41 @@ function testDivisors(low, high) {
6868
}
6969

7070
testDivisors(2, 10);
71+
72+
/**
73+
* Q006: Oddball sum
74+
* Write a function called oddball_sum which takes in a list of numbers and returns the sum of all the odd elements.
75+
* Try to solve with and without reduce function.
76+
*
77+
*/
78+
79+
function oddBallSumVariationNormal(numbs) {
80+
// Final count of all odd numbers added up
81+
let finalCount = 0;
82+
83+
// Loop through entire list
84+
for (let i = 0; i < numbs.length; i++) {
85+
// we divide by 2, and if there is a remainder then
86+
// the number must be odd so we add it to finalCount.
87+
88+
if (numbs[i] % 2 === 1) {
89+
finalCount += numbs[i];
90+
}
91+
}
92+
93+
return finalCount;
94+
}
95+
96+
oddBallSumVariationNormal([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]);
97+
98+
function oddBallSumVariationReduce(numbs) {
99+
return numbs.reduce((total, item) => {
100+
if (item % 2 === 1) {
101+
return (total += item);
102+
}
103+
104+
return total;
105+
}, 0);
106+
}
107+
108+
oddBallSumVariationReduce([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]);

0 commit comments

Comments
 (0)