类型错误:products.groupBy 不是函数

Yus*_*suf 7 javascript arrays node.js

我读到 JS 最近引入了一种新的数组方法groupBy来操作数组,例如

const products = [
  { name: 'apples', category: 'fruits' },
  { name: 'oranges', category: 'fruits' },
  { name: 'potatoes', category: 'vegetables' }
];
Run Code Online (Sandbox Code Playgroud)

这段代码

const groupByCategory = products.groupBy(product => {
  return product.category;
});
console.log(groupByCategory)
Run Code Online (Sandbox Code Playgroud)

应该产生这个输出

// {
//   'fruits': [
//     { name: 'apples', category: 'fruits' }, 
//     { name: 'oranges', category: 'fruits' },
//   ],
//   'vegetables': [
//     { name: 'potatoes', category: 'vegetables' }
//   ]
// }
Run Code Online (Sandbox Code Playgroud)

但是,我已经使用了日志node 18.7.0,但日志说TypeError: products.groupBy is not a function 我的问题此方法适用于任何节点版本吗?

请注意,我不使用reduce

Md *_*iar 9

Javascript Reduce() 方法使 Group By 像 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)} 
Run Code Online (Sandbox Code Playgroud)


KrL*_*iTs 2

由于您使用的功能处于测试状态,因此您必须使用 安装其依赖项npm i core-js,然后您可以通过导入来访问此功能。前任

require("core-js/actual/array/group-by-to-map");
require("core-js/actual/array/group-by");

const products = [
  { name: "apples", category: "fruits" },
  { name: "oranges", category: "fruits" },
  { name: "potatoes", category: "vegetables" }
];

const groupByCategory = products.groupBy((product) => {
  return product.category;
});

const groupByCategoryMap = products.groupByToMap((product) => {
  return product.category;
});

console.log(groupByCategory);
console.log(groupByCategoryMap);

Run Code Online (Sandbox Code Playgroud)

您可以在他们谈论其使用的同一个示例中看到这一点 如果您查看该论坛中给出的代码示例,则需要在此处导入和安装 core-js 。