Now in order to fill out getUserList, we're going to start by finding all of the users whose room matches the room argument specified. In order to do that we're going to use the filter method on arrays, which we've used in the past. Let's make a variable, we'll call it users and we'll set it equal to this.users, which is the array of users.filter:
getUserList (room) {
var users = this.users.filter((user) => {
})
}
Now if you remember filter takes a function as its argument. This function gets called with each individual user. We can return true to keep this item in the array or we can return false to have it removed from the array. I'm going to go ahead and return user.room, and we're going to check if that equals, using three equal signs, the room argument:
getUserList (room) {
var users = this.users.filter((user) => {
return user.room === room;
})
}
If they are equal, user.room === room is going to result in true that value will get returned; if they're not equal it's going to result in false and the user will not be added to the list above. Now we can go ahead and use the shortcut for our ES6 arrow function. Instead of adding the return keyword and specifying the actual arrow, we'll use the shorthand like this:
getUserList (room){
var users = this.users.filter((user) => user.room === room)
}
It's the exact same functionality just a different technique. Now we have a list of all the users who do match the criteria. The next step in the process is to take that array of objects and convert it to an array of strings. All we care about is getting that list of names. In order to do that, we're going to use map. I'm going to create a variable called namesArray and we're going to set this equal to users.map:
getUserList (room){
var users = this.users.filter((user) => user.room === room);
var namesArray = users.map
}
Now we have used map in the past, as we know map also takes a function similar to filter. It also gets called with the individual item. In this case, an individual user, but map lets us return the value we want to use instead. So we're going to get an object, it is going to have the id property, the room property and the name property, and all we want is the name property, so we're going to return user.name. And we can simplify that even further using the shorthand for the arrow function. user.name is going to be implicitly returned:
var users = this.users.filter((user) => user.room === room); var namesArray = users.map((user) => user.name);
Now that we have our namesArray array, all we need to do is go ahead and return it by returning namesArray:
getUserList (room){
var users = this.users.filter((user) => user.room === room);
var namesArray = users.map((user) => user.name);
return namesArray;
}
Now this is going to get the job done, before we simplify it any further let's go ahead and write a test case to make sure it works.