2👍
✅
You could try also this solution(a bit shorter):
//@ts-nocheck
const products = [
{
order_id: 1,
product_name: "apple",
},
{
order_id: 2,
product_name: "orange",
},
{
order_id: 3,
product_name: "orange",
},
{
order_id: 4,
product_name: "monster truck",
},
{
order_id: 5,
product_name: "spark plug",
},
{
order_id: 6,
product_name: "apple",
},
{
order_id: 7,
product_name: "can of peaches",
},
{
order_id: 8,
product_name: "monster truck",
},
{
order_id: 9,
product_name: "orange",
},
{
order_id: 10,
product_name: "orange",
},
];
const map = {};
products.forEach(
(product) =>
(map[product.product_name] = (map[product.product_name] ?? 0) + 1)
);
const Labels = Object.keys(map);
const Orders = Object.values(map);
console.log({ Labels, Orders });
1👍
const array = [
{
"order_id": 1,
"product_name": "apple"
},
{
"order_id": 2,
"product_name": "orange"
},
{
"order_id": 3,
"product_name": "orange"
},
{
"order_id": 4,
"product_name": "monster truck"
},
{
"order_id": 5,
"product_name": "spark plug"
},
{
"order_id": 6,
"product_name": "apple"
},
{
"order_id": 7,
"product_name": "can of peaches"
},
{
"order_id": 8,
"product_name": "monster truck"
},
{
"order_id": 9,
"product_name": "orange"
},
{
"order_id": 10,
"product_name": "orange"
}
];
const labels = [...new Set(array.map(value => value.product_name))];
const orders = labels.map(value => {
return array.reduce((previousValue, currentValue) => {
console.log(currentValue);
if (currentValue.product_name === value) {
return previousValue + 1;
}
else {
return previousValue;
}
}, 0);
});
Read about these array methods here:
- https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map
- https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce
The Set is used to only get an array of the unique values: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set/Set
But because the Set object doesn’t have these methods we transform it back to an Array using the spread operator (…)
Source:stackexchange.com