Problem:
const input = ['apple', 'banana', 'apple', 'orange', 'banana', 'apple'];
Solution:
const input = ['apple', 'banana', 'apple', 'orange', 'banana', 'apple'];
const result = {};
input.forEach(item => {
result[item] = (result[item] || 0) + 1;
});
console.log(result);
// { apple: 3, banana: 2, orange: 1 }
👉 How it works:
- Loop through each item.
- If it exists in
result, increment the count. - If not, initialize it to 1.
✅ Final Output:
{
apple: 3,
banana: 2,
orange: 1
}