Hi guys I'm stuck on a practice question, and really can't figure out a good solution.
The question is:
"The loopOverArray() function takes an array of directions as an argument and there is an empty object saved as a variable which stores each direction and how many times it was in the array. Using a for loop, this function needs to loop over each element in the array and update the object to show how many times each direction was found in the array."
The expected output should look like:
loopOverArray(["n", "s", "e", "e"] ==> returns {n: 1, s: 1, e: 2}
loopOverArray(["north", "south", "south", "north"] ==> returns {north: 2, south: 2}
loopOverArray([]) ==> returns {}
This is what i've tried so far. I'm new to JS so please forgive the very clumsy attempt.
function loopOverArray(directions) {
let ncount = 0;
let ecount = 0;
let scount = 0;
let wcount = 0;
for (let direction of directions) {
if (direction == "n") {
ncount += 1;
} else if (direction == "e") {
ecount += 1;
} else if (direction == "s") {
scount += 1;
} else {
wcount += 1;
}
}
console.log(`n: ${ncount}, s: ${scount}, e: ${ecount}, w: ${wcount}`)
}
loopOverArray(["n", "n", "s"]);
Problem is I think this doesn't satisfy the questions requirements properly, and its very ugly besides. There must be a better way. Any help would be humbly appreciated