Reputation: 5355
I am having an array that is having a product, an url and a state.
I would like to run it through a while-loop and with each run get only the objects that have a state = true
.
Currently I run in an endless loop:
const product = ['Product 1', 'Product 2']
const res = []
for (let i = 0; i < product.length; i++) {
res.push({
product: product[i],
url: 'price',
state: false,
}, {
product: product[i],
url: 'groceries/',
state: false,
}, {
product: product[i],
url: 'car',
state: false,
}, {
product: product[i],
url: 'automotive/',
state: false,
}, {
product: product[i],
url: 'computer/',
state: false,
})
}
function setState(res, state) {
res.state = state
}
function getState(res) {
return res.state
}
let currentState = res.filter(el => el.state = true)
let i = 0
while (currentState.length > 0) {
currentState = res.filter(el => el.state = true)
this.setState(res[i], false)
console.log(`Set state to false for ${JSON.stringify(res[i])}`)
console.log(currentState.length)
i++
}
Any suggestions how to get only the objects where the state = true
and set the state after each run to true so that my loop terminates?
I appreciate your replies!
Upvotes: 0
Views: 46
Reputation: 516
Two issues here your using = instead of == and your rechecking for states too early
It should also be noted that you really dont need == true it can just be res.filter(el => el.state)
let currentState = res.filter(el => el.state == true)
let i = 0
while (currentState.length > 0) {
this.setState(res[i], false)
currentState = res.filter(el => el.state == true)
console.log(`Set state to false for ${JSON.stringify(res[i])}`)
console.log(currentState.length)
i++
}
Upvotes: 2
Reputation: 305
You are doing
array.filter(e1=> e1.state = true)
e1.state = true assigns e1.state value to true and returns the value that is assigned.
Filter return those elements which returns true.
Since every elements state is being assigned true and always true is returned, it returns the same array instead of filtering it.
Use
array.filter(e1=> e1.state == true)
Upvotes: 1
Reputation: 594
Your problem is that you are setting all the elements' state to true by using =
(the assignment operator) instead of ==
or ===
which are comparison operators.
In your particular situation, it doesn't look like you need either one, because el.state is a boolean anyway, so you can just do res.filter(el => el.state)
Upvotes: 1