Reputation: 51
I know how filter
function works but this my first time encountering the use of filter in this way can someone explain to me how the isLost: true
objects are the only one being printed with the use of
!filtered || guest.isLost
?
const filtered=true
const users = [
{ name: "Jack", isLost: true },
{ name: "Sawyer", isLost: true },
{ name: "Lupin", isLost: false }
];
const filteredUsers = users.filter(user => !filtered || user.isLost).map(user => user)
console.log(filteredUsers)
console:
[{"name":"Jack","isLost":true},{"name":"Sawyer","isLost":true}]
Upvotes: 0
Views: 58
Reputation: 63
!filterd
is always false. So your condition is only true if isLost is true
If you want to filter out everything that has the property isLost:true
Use this condition
!user.isLost
const users = [
{ name: "Jack", isLost: true },
{ name: "Sawyer", isLost: true },
{ name: "Lupin", isLost: false }
];
const filteredUsers = users.filter(user => !user.isLost)
console.log(filteredUsers)
Upvotes: 1
Reputation: 4667
expr1 || epxr2
returns expr1
if it can be evaluate to true, else it returns expr2
In your case, as filtered
is true (then !filtered
is false), the filter works with the value of user.isLost
Upvotes: 1
Reputation: 72336
filtered
is initialized with true
and never modified.
Consequently, ! filtered
is always false
and false || x
is the same as x
.
And that means the filter condition is user.isLost
.
Because .map(user => user)
does not have any effect, your code has the same effect as:
const filteredUsers = users.filter(user => user.isLost)
Upvotes: 0