Categories
JavaScript Answers

How to partition an array in JavaScript?

Spread the love

Sometimes, we want to partition an array in JavaScript.

In this article, we’ll look at how to partition an array in JavaScript.

How to partition an array in JavaScript?

To partition an array in JavaScript, we can use the Lodash chunk function.

For instance, we write:

const arrayAll = [1, 2, 3, 4, 5, 6, 7, 8, 9]
const chunked = _.chunk(arrayAll, 3)
console.log(chunked)

to call chunk with arrayAll and 3 to return an array with entries in arrayAll divided into chunks of 3.

As a result, chunked is:

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

Conclusion

To partition an array in JavaScript, we can use the Lodash chunk function.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *