Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Map an Array by every two elements

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.

like image 601
jobiin Avatar asked Mar 26 '18 12:03

jobiin


1 Answers

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])))
like image 112
Matthew Lowe Avatar answered Oct 22 '22 00:10

Matthew Lowe