w3resource

JavaScript: Chunk an array into smaller arrays of a specified size

JavaScript fundamental (ES6 Syntax): Exercise-265 with Solution

Write a JavaScript program to chunk an array into smaller arrays of a specified size.

Sample Solution:

HTML Code:

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>Chunk an array into smaller arrays of a specified size</title>
</head>
<body>

</body>
</html>

JavaScript Code:

//#Source https://bit.ly/2neWfJ2 
const chunk = (arr, size) =>
  Array.from({ length: Math.ceil(arr.length / size) }, (v, i) =>
    arr.slice(i * size, i * size + size)
  );
console.log(chunk([1, 2, 3, 4, 5], 2));

Sample Output:

[[1,2],[3,4],[5]]

Pictorial Presentation:

JavaScript Fundamental: Chunk an array into smaller arrays of a specified size.

Flowchart:

flowchart: Chunk an array into smaller arrays of a specified size.

Live Demo:

See the Pen javascript-basic-exercise-265-1 by w3resource (@w3resource) on CodePen.


Improve this sample solution and post your code through Disqus

Previous: Write a JavaScript program to capitalize the first letter of every word in a string.
Next: Write a JavaScript program to clamp number within the inclusive range specified by the given boundary values a and b.

What is the difficulty level of this exercise?



JavaScript: Tips of the Day

Removes elements in an array until the passed function returns true. Returns the removed elements.

Example:

const tips_remove = (arr, func) => {
  for (const [i, val] of arr.entries()) if (func(val)) return arr.slice(0, i);
  return arr;
};

console.log(tips_remove([1, 2, 3, 4, 5, 6], n => n >= 5));

Output:

[1, 2, 3, 4]