-1

Hi so I have this array of objects:

const employees = [
    {age: 35, name: "David" position: "Front-End"},
    {age: 24, name: "Patrick" position: "Back-End"},
    {age: 22, name: "Jonathan" position: "Front-End"},
    {age: 32, name: "Raphael" position: "Full-Stack"},
    {age: 44, name: "Cole" position: "Back-End"},
    {age: 28, name: "Michael" position: "Front-End"},
]

and I want to get a result like this:

const employees = [
    {position: "Front-End", count: 3},
    {position: "Back-End", count: 2},
    {position: "Full-Stack", count: 1},
]

how is that possible to do with that result or the most similar one?

dylanb15
  • 25
  • 6
  • very related: [How to count duplicate value in an array in javascript](https://stackoverflow.com/questions/19395257/how-to-count-duplicate-value-in-an-array-in-javascript) and [How to check how many times a value appears in an array?](https://stackoverflow.com/questions/22995391/how-to-check-how-many-times-a-value-appears-in-an-array) – Pac0 Dec 09 '20 at 19:18
  • this link will work for you: [How to merge duplicates in an array of objects and sum a specific property?](https://stackoverflow.com/a/38294831/8929253) – sercan Dec 09 '20 at 19:21

1 Answers1

0

const employees = [
  { age: 35, name: 'David', position: 'Front-End' },
  { age: 24, name: 'Patrick', position: 'Back-End' },
  { age: 22, name: 'Jonathan', position: 'Front-End' },
  { age: 32, name: 'Raphael', position: 'Full-Stack' },
  { age: 44, name: 'Cole', position: 'Back-End' },
  { age: 28, name: 'Michael', position: 'Front-End' }
];

const obj = employees.reduce((val, cur) => {
  val[cur.position] = val[cur.position] ? val[cur.position] + 1 : 1;
  return val;
}, {});

const res = Object.keys(obj).map((key) => ({
  position: key,
  count: obj[key]
}));

console.log(res);
michael
  • 4,053
  • 2
  • 12
  • 31