-1

I have an array of strings that have duplicate values:

const = ['apple', 'orange', 'apple', 'apple', 'pear', 'pear']

What I would like to return is the following:

let occurrences = [{fruit: 'apple', numberOfOccurences: 3},{fruit: 'orange', numberOfOccurences: 1}, {fruit: pear, numberOfOccurences: 2}]

I have tried reduce and nested for loops but it is not returning the results I am expecting.

  • Please visit [help], take [tour] to see what and [ask]. Do some research, search for related topics on SO; if you get stuck, post a [mcve] of your attempt, noting input and expected output, preferably in a [Stacksnippet](https://blog.stackoverflow.com/2014/09/introducing-runnable-javascript-css-and-html-code-snippets/) – mplungjan Jun 01 '23 at 14:58
  • You should add what you've tried to the question. – Titus Jun 01 '23 at 14:59
  • 1
    There are tens of answers to this exact question on stack overflow – Jamiec Jun 01 '23 at 14:59
  • @jamiec if you can link to one, then great as I cannot find one that suits this scenario – user19031425 Jun 01 '23 at 15:00
  • 1
    make a [map](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map). for all `fruit` in your array, if map does not have fruit, set fruit to 1, otherwise get fruit and set fruit to fruit + 1. after iteration has completed, create the desired output from the map. – Mulan Jun 01 '23 at 15:03
  • 1
    Here is an example of what Mulan mentioned https://jsbin.com/dunoyezuho/edit?js,console – Titus Jun 01 '23 at 15:05

1 Answers1

-2

Quite trivial with reduce

const fruits = ['apple', 'orange', 'apple', 'apple', 'pear', 'pear'];

const stats = Object.values(fruits.reduce((acc,fruit) => {
  acc[fruit] ??= {fruit,num:0}
  acc[fruit].num++;
  return acc
},{}))
console.log(stats);
mplungjan
  • 169,008
  • 28
  • 173
  • 236