简体   繁体   中英

How to partition or divide an array (of objects) into specific number of chunks, possibly using lodash

I tried couple of way but not getting the result as expected.

Say that I have array of objects like this:

var users = [
  { 'user': 'barney', 'age': 36, 'active': false },
  { 'user': 'fred',   'age': 40, 'active': true },
  ... and so on (n lenght) ...
];

I wanted to divide them into two or three groups. If I have 100 objects and I like them to be divided in 3 groups, then the result with first and second group should contain 33 objects and the last group should contain 34 objects (or any other best possible way remaining objects distributed).

I tried to use lodash's chunk but that does things completly different :)

console.log(_.chunk(users, 2)) // this will create 50 chunks of 2 objects

Edited my question to explain more.

var my arrayOfObj = [1,2,3,4,5,6,7,8,9,10]
myArray.dividThemIn(3) // when run this, I am getting chunks like below
[{1,2,3}, {4,5,6}, {7,8,9}, {10}] // I am finding code that does this
[{1,2,3,4}, {5,6,7,8}, {9,10}] // But I need the code that does this

Divide the length of the array by the number of chunks you want (rounding up), and pass that into _.chunk as the second parameter:

var arrayOfObj = [1,2,3,4,5,6,7,8,9,10];
var chunks = _.chunk(arrayOfObj, Math.ceil(arrayOfObj.length / 3));
console.log(JSON.stringify(chunks)); //[[1,2,3,4],[5,6,7,8],[9,10]] 

You could use something like this.

function chunk (arr, chunks) {
    var chunked = [];
    var itemsPerChunk = Math.ceil(arr.length / chunks);

    while (arr.length > 0) {
        chunked.push(arr.slice(0, itemsPerChunk));
    }

    return chunked;
}

var data = [1,2,3,4,5,6,7,8,9,10];

chunk(data, 3);
// [[1,2,3,4], [5,6,7,8], [9,10]]

If you just want to split them into 3 groups without any criteria.

function splitIntoThree(arr){
  let result = [[],[],[]],
      thirds = Math.ceil(arr.length/3);

  arr.forEach((obj,index) => {
    if(index < thirds){
      result[0].push(obj);
    } else if(index < 2*thirds) {
      result[1].push(obj);
    } else {
      result[2].push(obj);
    }
  });

  return result;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM