You can find the frequency of each element in an array using a few common JavaScript approaches.
✅ 1. Using reduce() (Most Preferred)
const arr = ["apple", "banana", "apple", "orange", "banana", "apple"];
const freq = arr.reduce((acc, item) => {
acc[item] = (acc[item] || 0) + 1;
return acc;
}, {});
console.log(freq);
🔹 Output
{
apple: 3,
banana: 2,
orange: 1
}
🧠 Why it works
reduceloops once- Object stores counts
- Efficient and clean
✅ 2. Using a for loop
const freq = {};
for (let item of arr) {
freq[item] = (freq[item] || 0) + 1;
}
✔ Easy to understand
✔ Good for beginners
✅ 3. Using Map (Best for non-string keys)
const freqMap = new Map();
for (let item of arr) {
freqMap.set(item, (freqMap.get(item) || 0) + 1);
}
console.log(Object.fromEntries(freqMap));
✔ Preserves order
✔ Works with objects too
🎯 Short Interview Answer
To find frequency, iterate through the array and store counts in an object or Map. Each time an element appears, increment its count.
⭐ One-line summary
Use reduce() or a loop to count how many times each element appears in an array.