Count elements in an array | Javascript

 const myFruits = ['Apple','Orange','Mango','Banana','Apple','Apple','Mango']

//first option
const countMyFruits = myFruits.reduce((countFruits,fruit) => {
  countFruits[fruit] = ( countFruits[fruit] || 0 ) +1;
  return countFruits
 },{} )
 console.log(countMyFruits)
 // { Apple:3, Banana:1, Mango:2, Orange:1 }
 
 //seconf option
 const fruitsCounter = {};
 
 for( const fruit of myFruits ){
   fruitsCounter[fruit] = fruitsCounter[fruit] ? fruitsCounter[fruit]+1 :1;
 }
  
 console.log(fruitsCounter)
 // { Apple:3, Banana:1, Mango:2, Orange:1 } 

AI Explanation

This code snippet provides two options to create an object that stores the count of each fruit in the `myFruits` array. Both options achieve the same result, which is counting the occurrences of each fruit in the array and storing the count in an object. Explanation: 1. Option 1: - `reduce` method is used on the `myFruits` array to iterate through each element and accumulate the count of each fruit. - A callback function is provided to the `reduce` method. The callback function takes two parameters: `countFruits` (accumulator) and `fruit` (current element). - Inside the callback function, it checks if the `fruit` is already a key in the `countFruits` object. If yes, it increments the count, otherwise, it initializes the count to 1. - The updated `countFruits` object is returned at the end of each iteration. - The final result is logged to the console, which displays the object with fruit counts. 2. Option 2: - An empty object `fruitsCounter` is initialized to store the fruit counts. - A `for...of` loop is used to iterate through each fruit in the `myFruits` array. - For each fruit, it checks if the fruit is already a key in the `fruitsCounter` object. If yes, it increments the count, otherwise, it initializes the count to 1. - After iterating through all fruits, the `fruitsCounter` object contains the counts of each fruit. - The final result is logged to the console, displaying the object with fruit counts. Both options utilize different approaches (using `reduce` method vs `for...of` loop) to achieve the same result of counting the occurrences of each fruit in the array and storing the count in an object.