Skip to content

Instantly share code, notes, and snippets.

@IrhaAli
Created October 7, 2022 17:42
Show Gist options
  • Save IrhaAli/1228a5bc932911476a49ee98a8e79381 to your computer and use it in GitHub Desktop.
Save IrhaAli/1228a5bc932911476a49ee98a8e79381 to your computer and use it in GitHub Desktop.
Sum the numbers in an array satisfying the given condition (even or odd)
function conditionalSum(data, cond){
let arraySize = data.length;
//special case
if (arraySize === 0){
return 0;
}
//determines which type of numbers need to be added (ie. odd or even)
let rem;
if (cond === 'even'){
rem = 0;
} else {
rem = 1;
}
//adds the appropriate numbers
let total = 0;
for (i = 0; i < arraySize; i++){
if (data[i] % 2 === rem){
total += data[i];
}
}
return total;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment