'Push array of objects that make up a count of 100
I have an array of objects like the following:
const items = [
{
'name': 'P1',
'value': 50
},
{
'name': 'P1',
'value': 49
},
{
'name': 'P2',
'value': 50
},
{
'name': 'P3',
'value': 50
}
]
I need to add up the values and then push into an array of objects only if the 1 or more objects make up a value total of 100.
Expected output:
const groupedItems = [
[
{
'name': 'P1',
'value': 50
},
{
'name': 'P1',
'value': 49
},
],
[
{
'name': 'P2',
'value': 50
},
{
'name': 'P3',
'value': 50
}
]
]
What I have tried:
const temp = [];
for (var i = 0; i < items.length; i++) {
if ((items[i] + items[i + 1]) < 100) {
temp.push(items[i]);
}
}
groupedItems.push(temp);
Solution 1:[1]
I guess i would approch your solution like this :
Each time retrieving the first array, reducing it and if the sum of the array + the value of your item is less than 100, pushing your item in the array.
Otherwise, pushing a new array in your groupedItems that contains your item.
There might be a better way of doing this but this is the main idea.
const items = [{
'name': 'P1',
'value': 50
},
{
'name': 'P1',
'value': 49
},
{
'name': 'P2',
'value': 50
},
{
'name': 'P3',
'value': 50
}
]
const groupedItems = []
items.forEach(item => {
if (groupedItems.length > 0) {
const lastArray = groupedItems[groupedItems.length - 1]
const sumLastArray = lastArray.reduce((total, current) => current.value + total,
0)
if (sumLastArray + item.value < 100) {
lastArray.push(item)
} else {
groupedItems.push([item])
}
} else {
groupedItems.push([item])
}
})
console.log(groupedItems)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | RenaudC5 |
