1

Let's say I have the following array:

const list = [{}, {}, {}, {}, {}, {}, {}, {}]

with lodash, I'd like to "group" these into three so I can sort them in react/js

// Map the grouped objects

group =>
<div>
     // Now map the three elements by one.
     item => 
    <div>item.value</div>
</div>

Here's my attempt:

  const mediaList = _.groupBy(media, (element, index) => {
    return Math.floor(index/3)
  })

Doesn't work, as all of the items are still grouped into one array and the name of the array is NaN.

How can I do this?

Emile Bergeron
  • 17,074
  • 5
  • 83
  • 129
oozy
  • 45
  • 1
  • 6

2 Answers2

5

You can use _.chunk to break it into array of chunks with 3 items.

const list = [{}, {}, {}, {}, {}, {}, {}, {}];

const result = _.chunk(list, 3);

console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.js"></script>
felixmosh
  • 32,615
  • 9
  • 69
  • 88
0

Using javascript we can chunk like this.

var result = chunkArray([1,2,3,4,5,6,7,8], 3);
console.log(result);

function chunkArray(myArray, chunk_size){
    var index = 0;
    var arrayLength = myArray.length;
    var tempArray = [];
    
    for (index = 0; index < arrayLength; index += chunk_size) {
        myChunk = myArray.slice(index, index+chunk_size);
        tempArray.push(myChunk);
    }

    return tempArray;
}
Yahiya
  • 761
  • 4
  • 15