-4

I have an array of fruits which has following elements

var fruits = ['Mango','Orange', 'Banana', 'Mango', 'Grapes', 'Orange', 'Apple', 'Apple', 'Banana', 'Mango']

And I want generate an output of object array which can be

result = [{fruit : 'Mango', Count : 3}, {fruit : 'Orange', Count : 2}, {fruit : 'Banana', Count : 2},{fruit : 'Grapes', Count : 1}, {fruit : 'Apple', Count : 2}]

How can I achieve the same?

Swapnil
  • 17
  • 4

3 Answers3

3

use reduce to create an object with keys as fruit name. If the key already exist increment the count else create an object with properties fruit and count, initialized to zero.

const fruits = ['Mango', 'Orange', 'Banana', 'Mango', 'Grapes', 'Orange', 'Apple', 'Apple', 'Banana', 'Mango'];

const output = Object.values(fruits.reduce((a, fruit) => {
  if (!a[fruit]) {
    a[fruit] = {
      fruit,
      count: 0
    };
  }
  a[fruit].count += 1;
  return a;
}, {}));

console.log(output);
random
  • 7,756
  • 3
  • 19
  • 25
1

First calculate individual fruits the count with the help of reduce() and finally convert that individual count to your expected object by map().

const fruits = ['Mango','Orange', 'Banana', 'Mango', 'Grapes', 'Orange', 'Apple', 'Apple', 'Banana', 'Mango']

const count = Object.values(fruits.reduce((old, cur) => (old[cur] = old[cur] || {fruit: cur, count: 0}, old[cur].count++, old), {}))

console.log(count)
MH2K9
  • 11,951
  • 7
  • 32
  • 49
0

try this:

const fruits = ['Mango', 'Orange', 'Banana', 'Mango', 'Grapes', 'Orange', 'Apple', 'Apple', 'Banana', 'Mango'];

const rst = Object.values(fruits.reduce((acc, ele) => (acc[ele] = {fruit: ele, count: (((acc[ele]||[])['count'])+=1) ||0}, acc),[]));

console.log(rst)
Ghoul Ahmed
  • 4,446
  • 1
  • 14
  • 23