filter array method javascript

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

Upvotes: 1

Views: 166

Answers (2)

slou
slou

Reputation: 34

)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

Upvotes: 0

Nina Scholz
Nina Scholz

Reputation: 386530

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);

Upvotes: 2

Related Questions