Skip to content

Instantly share code, notes, and snippets.

@jeanlucaslima
Last active February 26, 2021 12:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jeanlucaslima/6e1d7560c8baf34a830e7da752002382 to your computer and use it in GitHub Desktop.
Save jeanlucaslima/6e1d7560c8baf34a830e7da752002382 to your computer and use it in GitHub Desktop.
JavaScript quizz array
quiz([11, 9, 6, 11, 5], 3); // output: 26, 16
quiz([11, 9, 6, 11, 5, 1], 3); // output: 26, 17
quiz([11, 9, 6, 11, 5, 1, 1], 3); // output: 26, 17, 1
quiz([1, 2, 1, 3, 1, 4, 1, 5, 1], 2); // output: 3, 4, 5, 6, 1
// quiz sums every n elements of arr and print.
// also print the sum of any remaining elements
function quiz(arr, n) {
let response = [];
const reducer = (accumulator, currentValue) => accumulator + currentValue;
for (let i = 0; i < arr.length; i += n) {
let chunk = arr.slice(i, i + n); // breaks in parts
response.push(chunk.reduce(reducer)); // sums the parts, and adds to the array
}
console.log(response);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment