I have been working on a function that calculates the frequency distribution of an array. The aim is to output an object in which the keys represent the unique elements and the values show how frequently those elements appear.
Here's the code I've written so far:
function getFrequencies(arr) {
let obj = {};
for (let i=0; i<arr.length; i++){
let element = arr[i];
console.log(element)
// check if key exists in the object already
// if it does, increment its value by 1
if (obj[element] !== undefined){
obj[element] += 1;
}
// if it doesn't, set the initial value to 1
else {
obj[element] === 1;
}
}
return obj
}
Upon calling getFrequencies(["A", "B", "A", "A", "A"]), my current code gives an empty object instead of the expected result:
{ A: 4, B: 1 }
I'm wondering what errors might be present in my implementation?