I was reading that JS recently introduced a new array method groupBy to manipulate an array such
const products = [
{ name: 'apples', category: 'fruits' },
{ name: 'oranges', category: 'fruits' },
{ name: 'potatoes', category: 'vegetables' }
];
the that this code
const groupByCategory = products.groupBy(product => {
return product.category;
});
console.log(groupByCategory)
should produce this output
// {
// 'fruits': [
// { name: 'apples', category: 'fruits' },
// { name: 'oranges', category: 'fruits' },
// ],
// 'vegetables': [
// { name: 'potatoes', category: 'vegetables' }
// ]
// }
however, I have used node 18.7.0 but the log saying TypeError: products.groupBy is not a function
My question does this method works on any of node version?
Note that I don't to use reduce
const products = [
{ name: 'apples', category: 'fruits' },
{ name: 'oranges', category: 'fruits' },
{ name: 'potatoes', category: 'vegetables' }
];
var result = products.reduce((x, y) => {
(x[y.category] = (x[y.category] || [])).push(y);
return x;
}, {});
console.log(result);
Output:
{fruits: Array(2), vegetables: Array(1)}
{"fruits":[{"name":"apples","category":"fruits"},
{"name":"oranges","category":"fruits"}],
"vegetables":[{"name":"potatoes","category":"vegetables"}]}
const products = [
{ name: 'apples', category: 'fruits' },
{ name: 'oranges', category: 'fruits' },
{ name: 'potatoes', category: 'vegetables' }
];
var obj = {};
$(products).each(function (index, value) {
if (obj[value.category] == undefined) {
obj[value.category] = [];
}
obj[value.category].push(value);
});
console.log(obj); //same output
var obj = Object.groupBy(products, x => x.category);
console.log(obj);
groupBy is not a function in Node.js. You should first import it and then use it.
npm i core-jsimport { groupBy } from "core-js/actual/array/group-by";
const groupByCategoryMap = products.groupBy(product => product.category);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With