I have the following object/array:
[
{
"id": null,
"value": "Apples",
"label": "Apples",
"Quantity": 1,
"Weight": "0.075",
"inputQuantity": "2",
"Category": "BREAKFAST",
"ItemCopy": 2,
"PM": "123"
},
{
"Quantity": 1,
"value": "Apples",
"Weight": "0.075",
"id": null,
"label": "Apples",
"inputQuantity": "3",
"Category": "BREAKFAST",
"ItemCopy": 2,
"PM": "123"
},
{
"value": "Asparagus",
"id": "TnwiO97ZHCsz4vl9A9OR",
"label": "Asparagus",
"Weight": "0.185",
"Quantity": 1,
"inputQuantity": "3",
"Category": "BREAKFAST",
"ItemCopy": 1,
"PM": "123"
}
]
I then use the following code to get them down to unique values:
function getUniqueDataCount(objArr, propName) {
const mi = [...objArr]
var data = [];
objArr.forEach(function (d, index) {
if (d[propName]) {
data.push(d[propName]);
}
});
var uniqueList = [...new Set(data)];
var dataSet = {};
for (var i = 0; i < data.length; i++) {
dataSet[uniqueList[i]] = data.filter(x => x == uniqueList[i]).length;
mi[i].ItemCopy = data.filter(x => x == data[i]).length
}
return mi;
}
useMemo(() => {
mydata = getUniqueDataCount(daataa, 'label');
}, [daataa])
useMemo(() => {
newCheck = Object.values(mydata?.reduce((acc, cur) => Object.assign(acc, { [cur?.label]: cur }), {}))
}, [mydata])
The newCheck object/array then becomes:
[
{
"Quantity": 1,
"value": "Apples",
"Weight": "0.075",
"id": null,
"label": "Apples",
"inputQuantity": "2",
"Category": "BREAKFAST",
"ItemCopy": 2
},
{
"value": "Asparagus",
"id": "TnwiO97ZHCsz4vl9A9OR",
"label": "Asparagus",
"Weight": "0.185",
"Quantity": 1,
"inputQuantity": "2",
"Category": "BREAKFAST",
"ItemCopy": 1
}
]
Which is more or less what I want, but within this newCheck object/array it is not calculating the inputQuantity correctly – it should be 5 for Apples, and 3 for Asparagus.
How do I modify this, so for every unique ingredient it gets the inputQuantity of every occurrence?
3
Answers
You just need to use
Array.reduce
method for efficient groupingCheck out this:
One way to accomplish this would be:
The input Array will be looped only once and the quantity will be converted into a number, to be able to sum the values of the entries.
I also face the same issue , but i didnt find any thing fruitfull