1

I have an array which looks like this:

fruits = ['Apple', 'Apple', 'Peach', 'Apple', 'Banana', 'Pear', 'Apple', 'Banana', 'Peach'];

Now I'm trying to count the containing elements to get a result which looks like this:

[
  ['Apple', 4],
  ['Peach', 2],
  ['Banana', 2],
  ['Pear', 1]
]

I was able to reduce it to a map. Like this:

fruits.reduce((acc, val) => acc.set(val, 1 + (acc.get(val) || 0)), new Map());

But I couldn't figure it out, how to create this array containing arrays.

Does anyone has an idea?

Nibor
  • 679
  • 1
  • 8
  • 18
  • 1
    You can use spread syntax `console.log([...fruits.reduce((acc, val) => acc.set(val, 1 + (acc.get(val) || 0)), new Map())])` – Nenad Vracar Feb 21 '18 at 11:24
  • wow ... i didn't know that you could use spread on a Map to get a result like that. – Magus Feb 21 '18 at 11:26

2 Answers2

1

You can try with Object.entires() method.

fruits = ['Apple', 'Apple', 'Peach', 'Apple', 'Banana', 'Pear', 'Apple', 'Banana', 'Peach'];

var results = Object.entries(fruits.reduce((acc, val) => {
  acc[val] = acc[val]+1 || 1;
  return acc;
},{}));
    
console.log(results);
fyasir
  • 2,924
  • 2
  • 23
  • 36
1

Map has an entries method that returns an iterator of key-value pairs. You can use Array.from if you require an array:

const fruits = ['Apple', 'Apple', 'Peach', 'Apple', 'Banana', 'Pear', 'Apple', 'Banana', 'Peach'];

const fruitMap = fruits
  .reduce((acc, val) => acc.set(val, 1 + (acc.get(val) || 0)), new Map());

// My preference because it's very clear what it does:
const fruitEntries = Array.from(fruitMap.entries());

// Other options:
/*
const fruitEntries = Array.from(fruitMap)
const fruitEntries = [...fruitMap];
*/


console.log(fruitEntries);
user3297291
  • 22,592
  • 4
  • 29
  • 45