[Easy] LeetCode JS 30 - 677. Chunk Array

March 7, 2024

☕️ Support Us
Your support will help us to continue to provide quality content.👉 Buy Me a Coffee

LeetCode 30 Days of JavaScript

This question is from LeetCode's 30 Days of JavaScript Challenge

2677. Chunk Array

Question Prompt

Imagine you're tasked with creating a function called chunk that segments an input array into smaller groups of specified lengths. Can you walk me through your approach to implementing this function, keeping the following requirements in mind:

  1. Function signature: chunk(array, [size=1])
  2. Input: An array to be divided (array) and an optional chunk size (size), defaulting to 1.
  3. Output: A new array containing the original array's elements grouped into sub-arrays with the specified size.
  4. Uneven division: If the array doesn't divide evenly, the last chunk includes any remaining elements.
  5. Original array preservation: The function should not alter the input array.
// Example usage
const originalArray = [1, 2, 3, 4, 5, 6, 7, 8, 9];
const chunkSize = 3;

// Output: [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
const chunkedArray = chunkArray(originalArray, chunkSize);

Solutions

Here is how we can implement the chunk. Creates an empty array temp to temporarily store elements for each chunk. Creates an empty array result to store the final array of chunks.

Iterates through each element of the input array using a for loop, and adds the current element to the temp array. Then, checks If temp has reached the desired size or if it's the last element in the array, it's time to create a chunk. We can do this by adding the current temp array (the chunk) to the result array.

Lastly, returns the result array containing the created chunks.

function chunk(array, size = 1) {
  let temp = [];
  const result = [];
  for (let i = 0; i < array.length; i++) {
    temp.push(array[i]);
    if (temp.length === size || i === array.length - 1) {
      result.push(temp);
      temp = [];
    }
  }
  return result;
}

Or we can use slice to make the implementation more concise. The slice method in JavaScript is used to create a shallow copy of a portion of an array into a new array object. It does not modify the original array. Instead, it returns a new array containing the extracted elements.

We can do the following with slice

  • The chunkArray function iterates over the array using a for loop.
  • In each iteration, it uses the slice method to create a sub-array starting from the current index i and ending at i + size.
  • This sub-array is then pushed into the chunkedArr.
  • Once all elements have been processed, the function returns the array of chunks.
function chunkArray(array, size) {
  const chunkedArr = [];

  // Iterate over the array elements
  for (let i = 0; i < array.length; i += size) {
    // Slice out a chunk and push it into the chunkedArr
    chunkedArr.push(array.slice(i, i + size));
  }

  // Return the array of chunks
  return chunkedArr;
}
☕️ Support Us
Your support will help us to continue to provide quality content.👉 Buy Me a Coffee