Last active
February 26, 2021 12:29
-
-
Save jeanlucaslima/6e1d7560c8baf34a830e7da752002382 to your computer and use it in GitHub Desktop.
JavaScript quizz array
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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