From 28e633e89aea9aef6a818964d3c75772fd08a10e Mon Sep 17 00:00:00 2001 From: Matej Focko Date: Sat, 3 Jun 2023 20:44:27 +0200 Subject: [PATCH] =?UTF-8?q?problems(js):=20add=20=E2=80=9C2677.=20Chunk=20?= =?UTF-8?q?Array=E2=80=9D?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Matej Focko --- problems/js/chunk-array.js | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) create mode 100644 problems/js/chunk-array.js diff --git a/problems/js/chunk-array.js b/problems/js/chunk-array.js new file mode 100644 index 0000000..a66d3df --- /dev/null +++ b/problems/js/chunk-array.js @@ -0,0 +1,24 @@ +/** + * @param {Array} arr + * @param {number} size + * @return {Array[]} + */ +var chunk = function(arr, size) { + let chunked = []; + + let current = new Array(); + for (let i = 0; i < arr.length; ++i) { + current.push(arr[i]); + + if ((i + 1) % size == 0) { + chunked.push(current); + current = new Array(); + } + } + + if (current.length > 0) { + chunked.push(current); + } + + return chunked; +};