I need to dynamically filter an array...help?!

Tell us what’s happening:

Your code so far


class MyComponent extends React.Component {
constructor(props) {
  super(props);
  this.state = {
    users: [
      {
        username: 'Jeff',
        online: true
      },
      {
        username: 'Alan',
        online: false
      },
      {
        username: 'Mary',
        online: true
      },
      {
        username: 'Jim',
        online: false
      },
      {
        username: 'Sara',
        online: true
      },
      {
        username: 'Laura',
        online: true
      }
    ]
  }
}
render() {
  const usersOnline = this.state.users.filter(i => i.online == true); // change code here
  const renderOnline = usersOnline.map((i) => <li key={i.userName + 1}>{i.userName}</li>); // change code here
  return (
     <div>
       <h1>Current Online Users:</h1>
       <ul>
         {renderOnline}
       </ul>
     </div>
  );
}
};

Your browser information:

User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.13; rv:76.0) Gecko/20100101 Firefox/76.0.

Challenge: Use Array.filter() to Dynamically Filter an Array

Link to the challenge:

what did I do wrong? Thank you!

Hello!
The problem lies here:

usersOnline.map((i) => <li key={i.userName + 1}>{i.userName}</li>);
// userName should be username:
// usersOnline.map((i) => <li key={i.username + 1}>{i.username}</li>);

By the way, do you realize that the key attribute ends up with a value like Jeff1, Mary1, Sara1 and Laura1? The Array.map callback function receives up to three arguments:

  1. The current element of the array. In this case, each user.
  2. The index of the element on the array. A successive value that starts at 0.
  3. And the iterated array.

So, if you wanted to add an incrementing value to the key, you would write something like this:

usersOnline.map((item, index) => <li key={item.username + index}>{item.username}</li>) // Verbose, but easier to understand

Anyways, I hope it helps :slight_smile:,

Stay safe!

1 Like

Thank you! I’m off to bed, but I’ll work on this tomorrow!

1 Like

Thank you! It worked. On to the last challenge for this section! (Thank heavens)

1 Like