Return 具有相同值的新对象数组按 qauntity/length 分组

Return a new array of objects with same values grouped by qauntity/length

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

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

我想变形数组,使其成为一个对象数组,其中 key/vals 确定重复项的值。

目前我有

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

任何人都可以告诉我我在做什么吗wrong/missing?

您可以使用 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);

您可以使用 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);