Skip to content

Instantly share code, notes, and snippets.

@TCotton
Created August 12, 2017 19:33
Show Gist options
  • Save TCotton/f9f92dd9b64f58b35198538b36a0fd9d to your computer and use it in GitHub Desktop.
Save TCotton/f9f92dd9b64f58b35198538b36a0fd9d to your computer and use it in GitHub Desktop.
#1: I need to go over an array and get a single value as a result
// for loop
const sum = (array) => {
let result = 0;
for (let i = 0; i < array.length; i++) {
result += array[i];
}
return result;
}
const numbers = [5, 25, 8, 18];
console.log(sum(numbers)); // logs 56
// reduce
const sum = (array) => array.reduce(
(total, current) => total + current,
0);
const numbers = [5, 25, 8, 18];
console.log(sum(numbers)); // logs 56
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment