Note: This tutorial also exist in my GitHub
You have a problem where you need to divide an array into a new array and slice it accordingly. How you want to solve this?
Well, we can use Chunk function in Lodash. It is a function that splits an array into smaller arrays.
It takes two arguments: the array to split and the size of each chunk. The function will returns an array of arrays. If the array cannot be split evenly, the final chunk will contain the remaining elements.
If you are not using Lodash, the solution that you can come out is
const myClassmates = ["John", "Jane", "Jack", "Jill", "Joe"];
const chunkSize = 2;
const newChunk = [];
for (let i = 0; i < myClassmates.length; i += chunkSize) {
const chunk = myClassmates.slice(i, i + chunkSize);
newChunk.push(chunk);
}
console.log("After Chunk: ", newChunk);
You will be probably using slice function to slice the array where
First argument - start index of the array to start the extraction
Second argument - Index of the first element in the array to exclude from the returned array
slice(start, end)
To know more about slicing, you can click here
But this solution is quite long and not very clean. Alternatively, now we will be using Lodash chunk function to solve the problem
Example:
const _ = require("lodash")
const myClassmates = ["John", "Jane", "Jack", "Jill", "Joe"];
console.log("Before Chunk: ", myClassmates);
const chunkResult = _.chunk(myClassmates, 2);
console.log("After Chunk: ", chunkResult);
It looks much cleaner right? Only 1 line of code. You just need to provide 2 arguments; the array and the chunk size that you want to slice it.
Okay, that's all for this week Lodash episode!
Thank you for reading :D
Psstt pstt :p
Do consider to love this article â€ïž and follow me! Why not right? It's FREE~
I would really appreciate it đšđ»âđ»
Will be posting more on things related to AWS, Javascript, Python, Serverless and more!
Top comments (0)