30-Jul-2022
.
Admin
Hi dev,
This article will provide some of the most important example node js split array into chunk example. this example will help you how to split an array into chunk in node js. We will use node.js split array into chunk example. I’m going to show you about node js split array using chunk function. You just need to some step to done chunk an array into smaller arrays of a specified size.
In this example node js split array into chunk example. This example is used to split into chunk of two array in array list.
let's see below simple example with output:
Install Node JS
This step is not required; however, if you have not created the node js app, then you may go ahead and execute the below command:
mkdir my-app
cd my-app
npm init
index.js
Here’s a sample implementation for a chunk(items, size) function:
/**
* Split the `items` array into multiple, smaller arrays of the given `size`.
*
* @param {Array} items
* @param {Number} size
*
* @returns {Array[]}
*/
function chunk (items, size) {
chunk = []
//array concat
items = [].concat(items)
//while loop to let us loop through array to extract the chunk.
while (items.length) {
chunks.push(
items.splice(0, size)
)
}
return chunks
}
// create array list
items = [1, 2, 3, 4, 5, 6, 7, 8]
//split into chunk of two
myItem = chunk(items, 2)
console.log(myItem)
Output:
[ [ 1, 2 ], [ 3, 4 ], [ 5, 6 ], [ 7, 8 ] ]
It will help you...
#Node JS