I am using lodash, I wanted to group an array of objects according to the sum of it's property width.
I have this data set
[
{id: 0, width: 2},
{id: 1, width: 2},
{id: 2, width: 4},
{id: 3, width: 1},
{id: 4, width: 3}
]
Actually this is to build rows and columns, and the maximum width of a row is 4
The expected output would be:
[
[{id: 0, width: 2}, {id: 1, width: 2}],
[{id: 2, width: 4}],
[{id: 3, width: 1}, {id: 4, width: 3}]
]
How do I go about this?
Was thinking like:
const maxWidth = 4
let currentRowWidth = 0
let newData = _.map(source, data => {
let array = []
if (currentRowWidth === 0) {
currentRowWidth += data.width
...
...
}
})
Edge case:
- if for example the the current row width is 3, and the next column has a width of 2. . . then it should move to next row, since if we add 3 and 2... it will exceed 4.
e.g.
[
[{id: 0, width: 1}, {id: 1, width: 2}],
[{id: 2, width: 2} ...],
]