Q:

JS: Counting Elements in Array -> Returning Array of Arrays

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?

A:

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);

