After conducting thorough research, I couldn't find a solution to this particular problem on this platform. I'm intentionally avoiding specifics in order to solve it independently.
var arr = ['cat','car','cat','dog','car','dog']
function orgNums(input) {
var count = 0;
var obj = {};
for (var i = 0; i < input.length; i++) {
if (input[i] === 'cat')
obj['cat'] = count++;
}
return obj;
}
The desired output is {cat:2}
, but currently, I am getting {cat:1}
Ultimately, my goal is to have it return {cat:2, car:1, dog:2, gerbil:1}
I attempted to use obj[cat] = ++count
and successfully got the expected result. However, upon adding another if statement like
if input[i] === 'dog', obj[dog] = ++count
, the outcome became {cat:2, dog:4}
. It seems the count value persists throughout iterations. How can I reset it to zero each time?
EDIT: This new approach works perfectly var arr = ['cat', 'car', 'cat', 'dog', 'car', 'dog']
function orgNums(input) {
var obj = {};
for (var i = 0; i < input.length; i++) {
obj[input[i]] = obj[input[i]] || 0;
obj[input[i]]++;
}
return obj;
}
console.log(orgNums(arr));
However, my actual desired final output is:
[
{cat:1
dog:2
}
{car:2
}
]
Attempting to integrate an if statement like this:
if (input[i] === 'cat'||'dog')
still includes car
in the object. I will continue exploring how to handle multiple objects within the array. Thank you once again!