Lets say I have an array of services objects
services: [{title: title, caption: caption},{title: title, caption: caption},{title: title, caption: caption},{title: title, caption: caption}]
The end result is a mapped array with every two elements in it's own div.
<div>
<div>services[0]</div>
<div>services[1]</div>
</div>
<div>
<div>services[2]</div>
<div>services[3]</div>
</div>
I cant wrap my head around how I would achieve this? Map and split the array by every two elements? Split the array into two arrays, then map that? Is it to early in the morning? Yes it is.
Yes, one way to do it is to group the array by every two elements, but you'd do that by using reduce
first, and then using map
.
The callback for reduce
can actually take four arguments, and you can initialize the accumulator with an empty array, so it ends up looking like this:
services = [{
title: 'title0',
caption: 'caption0'
}, {
title: 'title1',
caption: 'caption1'
}, {
title: 'title2',
caption: 'caption2'
}, {
title: 'title3',
caption: 'caption3'
}];
services.reduce(
function(accumulator, currentValue, currentIndex, array) {
if (currentIndex % 2 === 0)
accumulator.push(array.slice(currentIndex, currentIndex + 2));
return accumulator;
}, []).map(p => (console.log(p[0], p[1])))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With