I have the code below, which looks fine to me but keeps returning 0. I need to iterate through the named users in the user object and return the total number of users that have an online property value of true.
I've tried changing the newUser variable to an array and pushing the user into that array of online has a value of true, then returning the length of the array and it returns 0 as well.
let users = {
Alan: {
age: 27,
online: false
},
Jeff: {
age: 32,
online: true
},
Sarah: {
age: 48,
online: false
},
Ryan: {
age: 19,
online: true
}
};
function countOnline(obj) {
// change code below this line
const newUser = 0;
for (let user in obj) {
if (user.online === true) {
} else {
newUser++;
}
}
return newUser;
// change code above this line
}
console.log(countOnline(users));
I'm expecting the for-in loop to iterate through the users in the user object and if there is a property of online with a value of true to increment the newUser varibale by 1 each time and then return the newUser variable with a value of 2. But it keeps returning 0.
You can use Array.reduce to reduce the array of users to a number
const count = Object.keys(users).reduce((accum, username) => users[username].online ? accum + 1 : accum, 0)
or Array.filter to get the length of a filtered array of online users
const count = Object.keys(users).filter(username => users[username].online).length;
o(n) solution without converting the object keys to an array
let count = 0
for (const username in users) {
count = users[username].online ? count + 1 : count
}
return count