Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeError: products.groupBy is not a function

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

like image 238
Yusuf Avatar asked Jul 13 '26 12:07

Yusuf


2 Answers

Javascript Reduce() method to make Group By Like SQL

            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"}]}

The simple solution without reduce method is:

        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

Or most easy way:

var obj = Object.groupBy(products, x => x.category);

console.log(obj);
like image 69
Md Shahriar Avatar answered Jul 15 '26 03:07

Md Shahriar


groupBy is not a function in Node.js. You should first import it and then use it.

  • First, install: npm i core-js
  • Then, import:
    import { groupBy } from "core-js/actual/array/group-by";
    
    const groupByCategoryMap = products.groupBy(product => product.category);
    
like image 24
Shahin Movassagh Avatar answered Jul 15 '26 03:07

Shahin Movassagh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!