I have been tasked with a counting challenge which I should return an object containing a count of elements in the array. for e.g.
expect(createTally(['a', 'b', 'a'])).to.eql({ a: 2, b: 1 });
So I have managed to do this with the higher-order function reduce but I want to be able to do this with a for loop so I can really see how this works, my code for the reduce method is below...
const createTally = items => {
const counter = items.reduce((acc, curr) => {
acc[curr] = (acc[curr] || 0) + 1
return acc
}, {})
return counter
}
So far for my for loop I have ...
const createTally = items => {
const tally = {};
let count = 0
if (items.length > 0) {
for (let i = 0; i < items.length; i++) {
if (items[i].length > count) {
count += count + 1
console.log(count)
}
const key = items[i]
tally[key] = count
return tally
}
} else {
return tally;
}
}
I am struggling to increment my count and not passing any tests other than being able to return an empty object when passed an empty array and passing 1 key value pair when given a single element, any help would be much appreciated, thank you