I find this excercice (inside the Alchemy JS course) about how to get the duplicates from a given Array. I found many ways to solve this over stackoverflow but any of them work inside the solving course. Anyway: Can anyone explain how this works?
Thanks again.
–>> the alchemy solving answer was this:
function countElements(elements) {
let elementCount = {};
for(let i = 0; i < elements.length; i++) {
if(!elementCount[elements[i]]) {
elementCount[elements[i]] = 1;
} else {
elementCount[elements[i]] += 1;
}
}
return elementCount;
}
BUT LOOK AT THE TASK:
Write a function countElements that takes in an array and returns an object a count of each element in the array.
const elements = ["e", "k", "e", "z", "i", "z"];
countElements(elements); // returns {e: 2, k: 1, z: 2, i: 1}