How to group array elements into chunks in Javascript, reactjs & Lodash?

Total
0
Shares

Lodash provides _.chunk(array, size) function which is used to break array elements into group of equal sized chunks. For example –

// 👇 Split this array into chunks of 2 elements
arr = [a, b, c, d, e, f, g]

// 👇 Splitted array. Last element is single
arr = [[a, b], [c, d], [e, f], [g]]

The parameters of _.chunk(array, size) are –

  1. array – Array which you want to split
  2. size – Size of chunk

So, you can use the _.chunk function like this –

_.chunk(arr, 2)

// Output - [[a, b], [c, d], [e, f], [g]] 👈

Code Example

1. Using Javascript & Lodash

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

// Output 👉 - [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10]]

2. Using React & Lodash

import _ from 'lodash'

export default function App() {
  const arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

  return (
    <pre>
      {JSON.stringify(_.chunk(arr, 3), null, '\t')}
    </pre>
  )
}

// Output 👇
/*
[
	[
		1,
		2,
		3
	],
	[
		4,
		5,
		6
	],
	[
		7,
		8,
		9
	],
	[
		10
	]
]
*/

Live Demo

Open Live Demo