Reputation: 95
I have a button that's hidden until a condition is true
to check this, it has to look through a list (someList) to find any and all items that have needsApproval: true
then it checks in another array of items (data) to see if they're active
if everything is active we can show the button
is there a better way more modern way of doing this without multiple loops seems very inefficient?
const someList = [
{ id: 1, sid: 'a', needsApproval: true},
{ id: 2, sid: 'b', needsApproval: true},
{ id: 3, sid: 'c', needsApproval: false},
{ id: 4, sid: 'd', needsApproval: false}
]
const data = [
{ id: 1, sid: 'a', active: true},
{ id: 2, sid: 'b', active: false},
]
const needsApproval = someList.filter(x => x.needsApproval === true)
needsApproval.forEach(a => {
const found = data.find(s => s.sid === a.sid)
if (found && found.active === false) return false
})
return true
Upvotes: 2
Views: 52
Reputation: 782130
You're returning false
from the forEach
callback function, not from checkButton
. forEach
doesn't do anything with the return values of its function. So your checkButton()
function always returns true
.
You can use every()
to check whether a condition is true for all elements of an array.
const someList = [
{ id: 1, sid: 'a', needsApproval: true},
{ id: 2, sid: 'b', needsApproval: true},
{ id: 3, sid: 'c', needsApproval: false},
{ id: 4, sid: 'd', needsApproval: false}
]
const data = [
{ id: 1, sid: 'a', active: true},
{ id: 2, sid: 'b', active: false},
]
const checkButton = () => {
const needsApproval = someList.filter(x => x.needsApproval === true);
return needsApproval.every(a => {
const found = data.find(x => x.sid === a.sid);
return !(found && found.active === false);
});
}
console.log(checkButton());
Upvotes: 1