Nibor
Nibor

Reputation: 679

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?

Upvotes: 1

Views: 114

Answers (2)

fyasir
fyasir

Reputation: 2970

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

Upvotes: 1

user3297291
user3297291

Reputation: 23382

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

Upvotes: 1

Related Questions