How to get Users names from an Array

How to get Users names from an Array

Ok, let's say we have a list of users who are members of a health club. We want to view all members whose account is active and sorted by age in ascendant format.

To keep it simple for this demonstration, we have created an array of 4 items with the following properties

let users = [{
  id: 01,
  name: "Tom",
  isActive: true,
  age: 50,
},
{
  id: 02,
  name: "Callum",
  isActive: false,
  age: 23,
},
{
  id: 03,
  name: "Luke",
  isActive: true,
  age: 28,
},
{
  id: 04,
  name: "Lucy",
  isActive: true,
  age: 45,
}];

Let's break this into small chunks and solve it one at a time

  1. We want to view all members = users' names
  2. whose account is active = isActive status
  3. Sorted by age in ascendant format = sort age

Now that we have broken down into small chunks we can start to work on our code

To view all the users we can loop through each user in the array and copy names into a new array. The tasks we need to accomplish at this point are

a) Loop through each user in the array = we can use the for() Loop method b) Copy all names into a new array = create a new array and use the push() method

Using the for() method we can loop through the “users” array and view each user

for(i = 0; i < users.length; i++){
    console.log(users[i].name);
  }

result: 
"Tom"
"Callum"
"luke"
"Lucy"

The next step is to get all users' names into a new array. We create an empty array of “names” and use the push() method to push all the names into the array

let names = [];
for(i = 0; i < users.length; i++){
    names.push(users[i].name);
  }

console.log(names) to view all the names in the console

Your result should be [“Tom”, “Callum”, “Luke”, “Lucy”]

Our next step is to list all the users whose account is still active. This means if the user isActive property has the value of true then push the name to the new array. We can do this, by using an If () statement and the condition “users[i].isActive”

let names = [];
for(i = 0; i < users.length; i++){
  if(users[i].isActive){
    names.push(users[i].name);
  }
}

Your result should be [“Tom”, “Luke”, “Lucy”]

At this point, we have solved two parts of our solution

  1. We want to view all members = users' names
  2. whose account is active = isActive status

Great job and congratulations!, You have managed to return the active users' names, but can you do better with your code?

Let's look at the forEach() method instead of using the for() loop method

The example below is simple to understand and has less code than our for() loop method. Again, we create an empty Array and in this example, we name it “forEachName”. The forEach method will loop through each item (user) in the array and run a function push.(user.name) into the array named “forEachName”.

let forEachName = [];
users.forEach((user) => {
  forEachName.push(user.name)
});

The result is a list of names [“Tom”, “Callum”, “Luke”, “Lucy”].

Let us take this a step further and use the map() method instead of forEach()

const mapMethod = users.map((user) => user.name)

The map method returns a new array of user names (user.name). Using the map method to achieve part 1 of our solution, we have managed to keep the code to one line.

Note: we do not need the [i] after user. The map() method automatically iterates through each item.

Part 2 of our solution is completed by using the filter() method and the result is a list of active user names.

Keeping with this line of code we can combine it with the .filter() method to filter through the user's array and only include the active users. Similar to the map () method we run a function on each item in the array and return user.isActive (users that are active)

The names of each user are returned using the map() method

const mapMethod = filter.users((user) => users.isActive).map((user) => users.name)

Part 3

Continuing the line of code and returning active user names sorted by age in ascending order.

We need to sort users by age in ascending format. We can use the sort() method to do this as shown below.

users.sort((user1, user2) => (user1 < user2 ? -1 : 1))

The sort method can be a little tricky. Sort () by default, sorts values by strings. This works well for strings ("Bus" comes before "Car"). However, if numbers are sorted as strings, "35" is bigger than "200", because "3" is bigger than "2". Because of this, the sort() method will produce an incorrect result when sorting numbers. To help solve this, we can use a compare function “function(a, b)” and {return what we require}

a = item in the array and b = next item in the array.

You can read more about the sort() method from w3schools.com

In our example, we compare the first user in our array to the second user and then the second user to the third user and so on until we get to the last user. In preference to (a, b) we use “user1” and “user2” (first item in the users array and then the next item in the users array)

//Sort, Filter & Map 
const mapMethod = users.sort((user1, user2)=> (user2.age < user1.age ? -1 : 1))
.filter((user) => user.isActive)
.map((user) => user.name)
console.log("map method1 " + mapMethod)

As you can see the code above, is easy to read and shorter. You can even set code on one line as shown below.

const mapMethod = users.sort((user1, user2)=> (user2.age < user1.age ? -1 : 1)).filter((user) => user.isActive).map((user) => user.name)

To achieve the same result using a for() loop method. Your code will be


const sortedUsers = users.sort((user1, user2)=> (user2.age < user1.age ? -1 : 1));
let names = [];
for(i = 0; i < sortedUsers.length; i++){
  if(sortedUsers[i].isActive){
    names.push(sortedUsers[i].name);
  }
}