Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
117
rated 0 times [  119] [ 2]  / answers: 1 / hits: 15613  / 6 Years ago, mon, march 26, 2018, 12:00:00

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.


More From » arrays

 Answers
13

Yes, one way to do it is to group the array by every two elements, but you'd do that by using reduce.


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:




const services = [{
title: 'title0',
caption: 'caption0'
}, {
title: 'title1',
caption: 'caption1'
}, {
title: 'title2',
caption: 'caption2'
}, {
title: 'title3',
caption: 'caption3'
}];

services
.reduce((accumulator, currentValue, currentIndex, array) => {
if (currentIndex % 2 === 0) {
accumulator.push(array.slice(currentIndex, currentIndex + 2));
}
return accumulator;
}, [])
.forEach(p => console.log(p[0], p[1]));




[#54852] Thursday, March 22, 2018, 6 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
briarc

Total Points: 402
Total Questions: 85
Total Answers: 114

Location: El Salvador
Member since Sun, Sep 12, 2021
3 Years ago
;