Search code examples
javascriptarraysobjectsplitchunks

split array of objects into three seperate array based on a property


I have a array of objects with property of id and size. Sum of objects size equals to 78 and I want to split this objects by three array. But I want to split possibly equal sum of size (~ 78/3 +-).

I have a this array of objects,

[
 {'id': '1', 'size': '10'},
 {'id': '2', 'size': '4'},
 {'id': '3', 'size': '6'},
 {'id': '4', 'size': '21'},
 {'id': '5', 'size': '2'},
 {'id': '6', 'size': '1'},
 {'id': '7', 'size': '6'},
 {'id': '8', 'size': '7'},
 {'id': '9', 'size': '8'},
 {'id': '1', 'size': '13'}
]

And I want

[
 [
  {'id': '4', 'size': '21'},
  {'id': '2', 'size': '4'}, 
  {'id': '6', 'size': '1'},
 ],
 [
  {'id': '1', 'size': '13'},
  {'id': '1', 'size': '10'},
  {'id': '5', 'size': '2'},
 ],
 [
  {'id': '3', 'size': '6'}, 
  {'id': '9', 'size': '8'},
  {'id': '7', 'size': '6'},
  {'id': '8', 'size': '7'},
 ]
]

Solution

  • This is an NP-complete problem so there is more then one solution. One approach I thought of is putting the bigger items first and then putting the smaller items where you have more space.

    let items = [
        {'id': '1', 'size': 10},
        {'id': '2', 'size': 4},
        {'id': '3', 'size': 6},
        {'id': '4', 'size': 21},
        {'id': '5', 'size': 2},
        {'id': '6', 'size': 1},
        {'id': '7', 'size': 6},
        {'id': '8', 'size': 7},
        {'id': '9', 'size': 8},
        {'id': '1', 'size': 13}
    ];
    //sort the array by size in reverse order
    items.sort((a, b)=> b.size - a.size);
    //array of sums
    let sums = [0,0,0];
    //final array of 3 arrays
    let arrays = [[],[],[]];
    for (let item of items) {
        //get index of the smallest sum
        let index =  sums.indexOf(Math.min.apply(null,sums));
        //add current item size to corresponding sum
        sums[index] += item.size;
        //add item to corresponding array
        arrays[index].push(item);
    }
    console.log(arrays);
    console.log(sums);