Introduction
Arrays are one the most used structures in JavaScript programming, which is why it's important to know its built-in methods like the back of your pocket.
In this tutorial, we'll take a look at how to split an array into chunks of n
size in JavaScript.
Specifically, we'll take a look at two approaches:
- Using the
slice()
method and afor
loop - Using the
splice()
method and awhile
loop
Splitting the Array Into Even Chunks Using slice() Method
The easiest way to extract a chunk of an array, or rather, to slice it up, is the slice()
method:
slice(start, end)
- Returns a part of the invoked array, between thestart
andend
indices.
Note: Both start
and end
can be negative integers, which just denotes that they're enumerated from the end of the array. -1
being the last element of the array, -2
being the next to last and so on...
The array returned by slice()
returns a shallow copy, meaning that any references within the original array will just be copied over as-is, and won't allocate memory for completely new objects.
So, to slice a list or array into even chunks, let's 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));
Running the code above yields the following output:
[[ 1, 2, 3 ], [ 4, 5, 6 ], [ 7, 8, 9 ], [ 10 ]]
In the code above, we break down arr
into smaller chunks of size 3
, by iterating through the array and slicing it every chunkSize
. In the last iteration, there'll be only one element (10
) left, which will have to make up its own chunk.
Splitting the Array Into Even Chunks Using splice() Method
Even though the splice()
method may seem similar to the slice()
method, its use and side-effects are very different. Let's take a closer look:
// Splice does the following two things:
// 1. Removes deleteCount elements starting from startIdx (in-place)
// 2. Inserts the provided new elements (newElem1, newElem2...) into myArray starting with index startIdx (also in-place)
// The return value of this method is an array that contains all the 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]
Let's see this in action through a code example:
Check out our hands-on, practical guide to learning Git, with best-practices, industry-accepted standards, and included cheat sheet. Stop Googling Git commands and actually learn it!
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));
Running this code yields:
[ [ 1, 2 ], [ 3, 4 ], [ 5, 6 ], [ 7, 8 ] ]
Here we are using a while
loop to traverse the array. In each iteration we perform the splicing operation and push each chunk into a resulting array until there are no more elements left in the original array (arr.length > 0
).
A very important thing to note is that splice()
changes the original array. where as slice()
creates a copy of the original array, so there won't be any change in the original one.
Conclusion
In this article, we have went over a couple of easy ways to split a list into even chunks in JavaScript. While doing so, we learned how to work with couple of built-in array methods like slice()
and splice()
.