How to split an array into even blocks using JavaScript

Posted by hasjem on Thu, 03 Mar 2022 18:32:42 +0100

Author: Abhilash Kakumanu
Translator: Front-end wit
Source: stackabuse

Have a dream, have dry goods, WeChat Search [Move the World] pays attention to this bowl-brushing wit that was still cleaning in the morning.

This article GitHub https://github.com/qq449245884/xiaozhi Included, there are complete test points, materials and my series of articles for first-line factory interviews.

Arrays are one of the most common structures in JavaScript programming, and that's why it's important to understand their built-in methods.

In this article, we will explore how to split an array into n blocks in JS.

Specifically, there are two main research methods:

  1. Using the slice() method and for loop
  2. Using the splice() method and the while loop

Using slice() method to split an array into even blocks

The slice() method is the easiest way to extract or slice an array block:

The slice(start, end) method returns a new array object, which is a shallow copy of the original array determined by begin and end (including begin, excluding end). The original array will not be changed.

Note: Both start and end can be negative integers, which only means they are enumerated from the end of the array. - 1 is the last element of the array, -2 is the second to last, and so on...

So to split a list or array into even blocks, we use the slice() method

function sliceIntoChunks(arr, chunkSize) {
    const res = [];
    for (let i = 0; i < arr.length; i += chunkSize) {
        const chunk = arr.slice(i, i + chunkSize);
        res.push(chunk);
    }
    return res;
}

const arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
console.log(sliceIntoChunks(arr, 3));

Run result:

[[ 1, 2, 3 ], [ 4, 5, 6 ], [ 7, 8, 9 ], [ 10 ]]

In the code above, we decompose the arr into small blocks of size 3 by traversing the array and slicing it by each chunkSize. In the last iteration, there was only one element left (10), so it formed a block of its own.

Using the splice() method to split an array into even blocks

Even though the splice() method looks similar to the slice () method, its usage and side effects are quite different. Let's take a closer look:

// splice does two things:
// 1. Delete deleteCount elements starting with startIdx
// 2. Insert the provided new element (newElem1, newElem2...) into myArray, starting with the index startIdx
// The return value of this method is an array containing all deleted elements

myArray.splice(startIdx, deleteCount, newElem1, newElem2...)

let arrTest = [2, 3, 1, 4]
let chunk = arrTest.splice(0,2)
console.log(chunk) // [2, 3]
console.log(arrTest) // [1, 4]

We actually understand this through a code sample:

function spliceIntoChunks(arr, chunkSize) {
    const res = [];
    while (arr.length > 0) {
        const chunk = arr.splice(0, chunkSize);
        res.push(chunk);
    }
    return res;
}

const arr = [1, 2, 3, 4, 5, 6, 7, 8];
console.log(spliceIntoChunks(arr, 2));

Run result:

[ [ 1, 2 ], [ 3, 4 ], [ 5, 6 ], [ 7, 8 ] ]

Here, we iterate through the array using a while loop. In each iteration, we splice and add each block to the result array until there are no more elements in the original array (arr.length > 0).

It is important to note that splice() changes the original array. If slice() creates a copy of the original array, no changes will be made to the original array.

summary

In this article, we introduce several simple methods for splitting lists into blocks in JS. During this process, we learned how to use several built-in array methods, such as slice() and splice().

~That's it. I'm going to brush the bowl. See you next time!

Original: https://stackabuse.com/how-to-split-an-array-into-even-chunks-in-javascript/

Communication

Have a dream, have dry goods, WeChat Search [Move the World] pays attention to this bowl-brushing wit that was still cleaning in the morning.

This article GitHub https://github.com/qq449245884/xiaozhi Included, there are complete test points, materials and my series of articles for first-line factory interviews.

Topics: Javascript Front-end Vue