I am trying to create a function that returns the frequency distribution of an array. This function should return an object, where the keys are the unique elements and the values are the frequency in which those elements occur.
My code is below:
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 object already
// if it exists, add 1 to the value
if (obj[element] !== undefined){
obj[element] += 1;
}
// if it does not exist, add 1 to setup future elements
else {
obj[element] === 1;
}
}
return obj
}
getFrequencies(["A", "B", "A", "A", "A"])
My code returns: {} when it should return:
{ A: 4, B: 1 }
What am I doing wrong?
Aucun commentaire:
Enregistrer un commentaire