Wednesday, January 22, 2025
HomeProgrammingSplit array into chunks - javascript

Split array into chunks – javascript

To split an array into smaller chunks of a specified size in JavaScript, you can create a reusable function. Below is a common and efficient approach:

Chunk Array Function

function chunkArray(array, size) {
  if (size <= 0) throw new Error("Chunk size must be greater than 0");
  const result = [];
  
  for (let i = 0; i < array.length; i += size) {
    result.push(array.slice(i, i + size));
  }
  
  return result;
}

// Example usage
const arr = [1, 2, 3, 4, 5, 6, 7, 8];
const chunked = chunkArray(arr, 3);

console.log(chunked); // Output: [[1, 2, 3], [4, 5, 6], [7, 8]]

Explanation:

  1. The function takes two parameters:
    • array: The array to split.
    • size: The size of each chunk.
  2. Inside the loop:
    • array.slice(i, i + size) creates a subarray starting at index i and ending at i + size (not inclusive).
    • Each chunk is pushed into the result array.
  3. The loop increments by the chunk size (i += size) to process the next chunk.
See also  JavaScript Arrays

Alternative Using reduce()

You can also use the Array.reduce() method to achieve the same result:

function chunkArray(array, size) {
  if (size <= 0) throw new Error("Chunk size must be greater than 0");
  return array.reduce((chunks, item, index) => {
    const chunkIndex = Math.floor(index / size);
    if (!chunks[chunkIndex]) {
      chunks[chunkIndex] = []; // Start a new chunk
    }
    chunks[chunkIndex].push(item);
    return chunks;
  }, []);
}

// Example usage
const arr = [1, 2, 3, 4, 5, 6, 7, 8];
const chunked = chunkArray(arr, 3);

console.log(chunked); // Output: [[1, 2, 3], [4, 5, 6], [7, 8]]

Explanation:

  • reduce() iterates over the array and groups elements into chunks.
  • Math.floor(index / size) determines the chunk index for the current item.
  • If the current chunk doesn’t exist, a new empty array is created.
  • The current item is added to the appropriate chunk.
See also  How do I use OpenSSL to Retrieve a Certificate from a Server?

Using Modern Libraries (Optional)

If you’re using a library like Lodash, it has a built-in chunk function:

Example with Lodash:

// Import lodash
const _ = require('lodash');

const arr = [1, 2, 3, 4, 5, 6, 7, 8];
const chunked = _.chunk(arr, 3);

console.log(chunked); // Output: [[1, 2, 3], [4, 5, 6], [7, 8]]

Lodash _.chunk Method:

  • Automatically handles edge cases.
  • Requires importing Lodash.

Edge Cases to Consider

  1. Empty Array:
    chunkArray([], 3); // Output: []
    
  2. Chunk Size Greater Than Array Length:
    chunkArray([1, 2, 3], 5); // Output: [[1, 2, 3]]
    
  3. Negative or Zero Chunk Size:
    chunkArray([1, 2, 3], 0); // Throws an error: "Chunk size must be greater than 0"
    

Both methods (using slice() or reduce()) are efficient and versatile. Choose the one that fits your coding style! Let me know if you’d like to explore further.

RELATED ARTICLES

Queues in C

Bash Sleep

0 0 votes
Article Rating

Leave a Reply

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
- Advertisment -

Most Popular

Recent Comments

0
Would love your thoughts, please comment.x
()
x