Sometimes, we want to split an array into array pairs in JavaScript.
In this article, we’ll look at how to split an array into array pairs in JavaScript.
Split an Array into Array Pairs in JavaScript
To split an array into array pairs in JavaScript, we can use the JavaScript array’s reduce
method.
For instance, we can write:
const initialArray = [2, 3, 4, 5, 6, 4, 3, 5, 5]
const newArr = initialArray.reduce((result, value, index, array) => {
if (index % 2 === 0) {
return [...result, array.slice(index, index + 2)];
}
return result
}, []);
console.log(newArr)
We have the initialArray
that we want to split into chunks of 2.
To do this, we call reduce
with a callback that returns the result
array that’s created from the result
array spread into a new array and an array with the next 2 items in the list if index
is event.
We get the next 2 items with the slice
with index
and index + 2
as the indexes.
Otherwise, we just return result
.
The 2nd argument is an empty array so result
is always an array.
As a result, newArr
is:
[
[
2,
3
],
[
4,
5
],
[
6,
4
],
[
3,
5
],
[
5
]
]
Conclusion
To split an array into array pairs in JavaScript, we can use the JavaScript array’s reduce
method.