BRUCE_FEBRUCE_FE

EN/CH Mode

BRUCE_FE JS Interview Notes - Implement Array Chunk Function

Learn how to implement array chunk function, split large arrays into equal-sized sub-arrays, and master practical techniques for data processing and pagination display.

ๅฝฑ็‰‡็ธฎๅœ–

Lazy to read articles? Then watch videos!

Array Chunk Function Overview

Array chunking is a common array processing technique that splits a large array into multiple smaller arrays (sub-arrays), each containing a specified number of elements. This is very useful when processing large amounts of data, batch operations, and pagination display.

Common Application Scenarios

  • 1. Pagination display: Split large amounts of data into multiple pages for display
  • 2. Batch processing: Split large tasks into small batches for execution, avoiding blocking
  • 3. API request optimization: Send large amounts of data in batches, avoiding oversized requests
  • 4. UI rendering optimization: Render large lists in batches to improve performance
  • 5. Data analysis: Split large datasets into manageable subsets for processing

Implement Basic Chunk Function

Below is a basic chunk function implementation that can split an array into sub-arrays of specified size:

function chunk(array, size) {
  if (!Array.isArray(array)) {
    throw new TypeError('Expected an array as the first argument');
  }
  
  if (size <= 0 || !Number.isInteger(size)) {
    throw new TypeError('Size must be a positive integer');
  }
  
  // ๅ‰ตๅปบ็ตๆžœ้™ฃๅˆ—
  const result = [];
  
  // ้ๆญทๅŽŸ้™ฃๅˆ—
  for (let i = 0; i < array.length; i += size) {
    // ไฝฟ็”จ slice ๆ–นๆณ•ๅ–ๅ‡บไธ€ๅ€‹ๅญ้™ฃๅˆ—
    result.push(array.slice(i, i + size));
  }
  
  return result;
}

// ไฝฟ็”จ็ฏ„ไพ‹
const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
console.log(chunk(numbers, 3));
// ่ผธๅ‡บ: [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10]]

The above implementation uses slice method to extract sub-arrays from the original array. We iterate through the array with the specified size as the step size, extracting size elements each time.

Practical Application Scenarios

Below are some practical application examples of array chunk functions:

1. Pagination Processing of Large Data

// Simulate large data from API
const allUsers = [/* Assume there are 1000 user data here */];

// Pagination display settings
const pageSize = 10;
const totalPages = Math.ceil(allUsers.length / pageSize);

// Get data for specified page number
function getPage(pageNumber) {
  // Check if page number is valid
  if (pageNumber < 1 || pageNumber > totalPages) {
    throw new Error('Invalid page number');
  }
  
  // Calculate start index (0-based)
  const startIndex = (pageNumber - 1) * pageSize;
  
  // Return page data
  return allUsers.slice(startIndex, startIndex + pageSize);
}

// Usage example
const page1 = getPage(1); // Get first page data
const page2 = getPage(2); // Get second page data

// Frontend pagination control
document.getElementById('prev-button').addEventListener('click', () => {
  if (currentPage > 1) {
    currentPage--;
    renderUsers(getPage(currentPage));
    updatePagination();
  }
});

document.getElementById('next-button').addEventListener('click', () => {
  if (currentPage < totalPages) {
    currentPage++;
    renderUsers(getPage(currentPage));
    updatePagination();
  }
});

2. Batch Processing API Requests

// Assume we need to process data for large amounts of IDs
const allIds = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, /* ... more IDs */];

// Batch processing function
async function processBatch(ids) {
  // Simulate API request
  console.log(`Processing batch of ${ids.length} ids: ${ids.join(', ')}`);
  
  // Assume this is an API call
  return fetch('/api/process', {
    method: 'POST',
    body: JSON.stringify({ ids }),
    headers: { 'Content-Type': 'application/json' }
  }).then(response => response.json());
}

// Process all IDs in batches
async function processAllIdsInBatches(ids, batchSize = 3) {
  const batches = chunk(ids, batchSize);
  const results = [];
  
  for (const batch of batches) {
    try {
      // Process each batch sequentially
      const result = await processBatch(batch);
      results.push(result);
      
      // Can add delay to avoid requests too fast
      await new Promise(resolve => setTimeout(resolve, 1000));
    } catch (error) {
      console.error(`Error processing batch ${batch}:`, error);
    }
  }
  
  return results.flat();
}

// Usage example
processAllIdsInBatches(allIds, 3)
  .then(results => console.log('All processing complete:', results))
  .catch(error => console.error('Processing failed:', error));