0

So i currently have an array like this:

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

I would like to morph the array so that it becomes an array of objects with key/vals that determine the value of the duplicates.

Currently i have got

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

however this code turns the array int this: [Bacon: 3, Steak: 2, Lettuce: 1, Cabbage: 3, Veal: 1] when ideally i want it to look like this: [{Bacon: 3}, {Steak: 2}, {Lettuce: 1}, {Cabbage: 3}, {Veal: 1}]

Can any1 please tell me what i'm doing wrong/missing?

Jim41Mavs
  • 482
  • 4
  • 21
  • Does this answer your question? [JavaScript ES6 - count duplicates to an Array of objects](https://stackoverflow.com/questions/49676897/javascript-es6-count-duplicates-to-an-array-of-objects) – PM 77-1 Dec 10 '20 at 21:40

2 Answers2

3

You could do it using reduce and map method.

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);
mr hr
  • 3,162
  • 2
  • 9
  • 19
2

You can do the following using reduce method,

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);
Md Sabbir Alam
  • 4,937
  • 3
  • 15
  • 30