1

could you please tell me why my script is broken? It is an exercise in a Udemy lesson. You need only returning users who have admin level access

var users = [
 { id: 1, admin: true },  
 { id: 2, admin: false },
 { id: 3, admin: false },
 { id: 4, admin: false },
 { id: 5, admin: true },
];

var filteredUsers;

function isAdmin(array, property){
     return array.filter(function(key){
        return key[property] === 'true';
})
}

filteredUsers = isAdmin(users, 'admin');

Thank you

  • 2
    `true !== 'true'` – SLaks Feb 02 '17 at 15:19
  • I think `isAdmin` is a "predicate," and should be used as the function inside .filter(). Also, calling it "isAdmin" *and* giving it the property name is redundant. Shouldn't isAdmin always know it should check the admin property? – Harry Pehkonen Feb 02 '17 at 16:21

2 Answers2

2

You need to test against a boolean value, because your data has true or false values.

return key[property] === true;
//                       ^^^^

function isAdmin(array, property) {
    return array.filter(function (key) {
        return key[property] === true;
        //                       ^^^^
    });
}

var users = [{ id: 1, admin: true }, { id: 2, admin: false }, { id: 3, admin: false }, { id: 4, admin: false }, { id: 5, admin: true }],
    filteredUsers = isAdmin(users, 'admin');

console.log(filteredUsers);
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
0

)Your problem is that your are using the 3 equal sing ("===") to test the proprety. Here's a link with more details that explains the difference between :

https://stackoverflow.com/a/523650/5235299

Community
  • 1
  • 1
slou
  • 34
  • 1
  • 6
  • Depends on your perspective. The way I see it, using the three equal signs is the correct thing to do, but you need to compare to `true`, not to `"true"`. But this may be a religious issue to some people (like myself ;D). – Harry Pehkonen Feb 02 '17 at 16:18
  • The problem was that I didn't realise the boolean values as property but strings. As Nina pointed it out I understood straight and realised my mistake. – László Péter Varga Feb 02 '17 at 19:18