I have a function called "howmanyOnline" that receives an object users.
Each user has a property online which is a boolean. It should return the number of users with the property online equal to true.
For example How many Online (users) returns 2 this the object of object:
let users = {
Victor: {
age: 33,
online: true
},
joan: {
age: 25,
online: true
},
frank: {
age: 25,
online: false
},
Emy: {
age: 24,
online: false
}
};
function howmanyOnline(users) {
}
How can I do this?
There are lots of ways you can do this, but the most common are one of either:
Use array.filter after grabbing the values from the object to filter down to only the users who are online, and then take the count of that array. This method takes a callback function, and is the more 'javascripty' way of doing this.
const values = {one: {a: 1}, two: {a: 2}, three: {a: 3}};
const arr = Object.values(values);
// filter down to only the elements which a value >= 2 under key 'a'
const filtered = arr.filter(obj => obj.a >= 2);
filtered.length; // 2
Start with a variable initialized to 0, then map or otherwise iterate across the object and increment the variable by 1 for every user who is online.
let count = 0;
const values = {one: {a: 1}, two: {a: 2}, three: {a: 3}};
// check if the value under key 'a' is >= 2, if so add 1 to count,
// otherwise add 0
for(value in values){count += values[value]['a'] >= 2 ? 1 : 0};
count; // 2
let users = {
Victor: {
age: 33,
online: true
},
joan: {
age: 25,
online: true
},
frank: {
age: 25,
online: false
},
Emy: {
age: 24,
online: false
}
};
function howmanyOnline(users) {
let count = 0;
for (const { online } of Object.values(users)) {
if (online) count += 1;
}
return count;
}
console.log(howmanyOnline(users));
This should work by using a for loop to get the online value and a if statement to check if it is true.
let users = {
Victor: {
age: 33,
online: true
},
joan: {
age: 25,
online: true
},
frank: {
age: 25,
online: false
},
Emy: {
age: 24,
online: false
}
};
let number =0
function howmanyOnline(users) {
for(let value of Object.values(users)){
if(value.online)
number++
}
return number
}
console.log(howmanyOnline(users))