【问题标题】:Return a new array of objects with same values grouped by qauntity/length返回按数量/长度分组的具有相同值的新对象数组
【发布时间】:2021-03-22 03:34:38
【问题描述】:

所以我目前有一个这样的数组:

const allMeats = ['Bacon','Bacon','Bacon', 'Steak', 'Lettuce', 'Cabbage','Cabbage','Cabbage','Steak', 'Veal']

我想对数组进行变形,使其成为一个对象数组,其键/值决定了重复项的值。

目前我有

const meatsGrouped = allMeats.reduce(
    (acum, cur) => Object.assign(acum, { [cur]: (acum[cur] || 0) + 1 }),
    [],
  );

然而,这段代码将数组转换为: [Bacon: 3, Steak: 2, Lettuce: 1, Cabbage: 3, Veal: 1] 理想情况下,我希望它看起来像这样: [{Bacon: 3}, {Steak: 2}, {Lettuce: 1}, {Cabbage: 3}, {Veal: 1}]

谁能告诉我我做错了什么/遗漏了什么?

【问题讨论】:

标签: javascript arrays javascript-objects reduce higher-order-functions


【解决方案1】:

你可以使用reduce和map方法来做到这一点。

const allMeats = [
  'Bacon',
  'Bacon',
  'Bacon',
  'Steak',
  'Lettuce',
  'Cabbage',
  'Cabbage',
  'Cabbage',
  'Steak',
  'Veal',
];

const ret = Object.entries(
  allMeats.reduce((prev, c) => {
    const p = prev;
    const key = c;
    p[key] = p[key] ?? 0;
    p[key] += 1;
    return p;
  }, {})
).map(([x, y]) => ({ [x]: y }));
console.log(ret);

【讨论】:

    【解决方案2】:

    您可以使用reduce方法执行以下操作,

    let allMeats = ['Bacon','Bacon','Bacon', 'Steak', 'Lettuce', 'Cabbage','Cabbage','Cabbage','Steak', 'Veal'];
    let res = allMeats.reduce((prev, curr) => {
      const index = prev.findIndex(item => item.hasOwnProperty(curr));
      if(index > -1) {
        prev[index][curr]++;
      }else {
        prev.push({[curr]: 1});
      }
      return prev;
    }, []);
    console.log(res);
    

    【讨论】:

      猜你喜欢
      • 2017-07-17
      • 2018-09-09
      • 1970-01-01
      • 2019-06-05
      • 1970-01-01
      • 1970-01-01
      • 2021-05-02
      • 1970-01-01
      • 2022-12-03
      相关资源
      最近更新 更多