Okay I researched this one and couldn't find an answer here so hopefully this isn't a duplicate. I'm also trying not to be specific in order to figure this out on my own.
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;
}
I want it to return {cat:2}
but I'm getting {cat:1}
Eventually I want it to return {cat:2, car:1, dog:2, gerbil:1}
So I tried using obj[cat] = ++count
and I'm getting the answer I want, but when I try a second if statement: if input[i] === 'dog', obj[dog] = ++count
I get {cat:2, dog:4}
. I noticed that it's taking what count
already is at, 0, then moves it to 2 to count cat, then moves it to 4, taking the dog count of 2 and adding 2 to it. How do I prevent that from happening so that count
restarts at 0 each time?
EDIT: So this works beautifully 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));
but the final output i actually want is:
[
{cat:1
dog:2
}
{car:2
}
]
So I tried throwing in an if statement like this:
if (input[i] === 'cat'||'dog')
but it's still throwing car
into the object. I'll try to figure out the multiple objects in the array. Thanks again!