-2

I'm doing a test in JavaScript. I'm asked to do the following:

function IsOffline (users, name) {
  // The function called "IsOffline" receives as an argument an array of objects called 'users' and a string called 'name'.
  // each object has a property 'name' which is a string and another called 'online' which is a boolean.
  // The function must return true if the user is offline, otherwise false.
  // ex:
  // var users = [
  // {
  // name: 'toni',
  // online: true
  //},
  // {
  // name: 'emi',
  // online: true
  //},
  // {
  // name: 'john',
  // online: false
  //}
  //];
  //
  // IsOffline (users, 'emi') return false

  // Your code here:
  

I'm a little lost and I don't know how to start. I appreciate any help.

Björn von TRITUM
  • 525
  • 1
  • 4
  • 16
  • Does this answer your question? [Find object by id in an array of JavaScript objects](https://stackoverflow.com/questions/7364150/find-object-by-id-in-an-array-of-javascript-objects) – Ivar Apr 09 '21 at 15:36
  • You have to look into the `users` array to find the item whose `name` property is equal to the `name` argument and return the opposite of that item's `online` property. Hint: you might want to look at `Array.prototype.find()` ([see on MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find)) – secan Apr 09 '21 at 15:39
  • For future reference, you might also want to have a look at [How do I ask and answer homework questions?](https://meta.stackoverflow.com/questions/334822/how-do-i-ask-and-answer-homework-questions) – secan Apr 09 '21 at 15:42

1 Answers1

0

You can use the Array.find() method which lets you search for an item in the array.

function IsOffline(users, name) {
  const foundUser = users.find(user => user.name === name)
  return foundUser ? !foundUser.online: "No user found";
}

var users = [
  { name: 'toni', online: true },
  { name: 'emi', online: true },
  { name: 'john', online: false },
];

// Online User
console.log(IsOffline(users, 'emi'))

// Offline User
console.log(IsOffline(users, 'john'))

// Unknown User
console.log(IsOffline(users, 'tom'))
Som Shekhar Mukherjee
  • 4,701
  • 1
  • 12
  • 28