const data = ['soccer', 'soccer', 'basketball', 'basketball', 'badminton', 'swimming', 'soccer', 'squash', 'badminton', 'swimming', 'soccer', 'squash', 'soccer', 'basketball', 'fencing'];
const sports = data.reduce(function(obj, item) {
if (!obj[item]) //to create an object if it doesn't exist
obj[item] = 0;
else
obj[item]++; //to increment the object count if it exist
return obj;
}, {});
console.log(sports);
Output I'm receiving:
Object { soccer: 0, basketball: 0, badminton: 0, swimming: 0, squash: 0, fencing: 0 }
Output I want:
Object { soccer: 5, basketball: 3, badminton: 2, swimming: 2, squash: 2, fencing: 1 }
What's going wrong?