I am using filter method for filtering data but it doesn’t work as my action.payload
is an array and I am using the forEach
method to loop through array of values. I don’t know where I am going wrong.
Below is my code:
const searchParameters = data && Object.keys(Object.assign({}, ...data));
action.payload.forEach((i) => {
filterData = state.products.filter((item) =>
searchParameters.some((parameter) =>
item[parameter]
.toString()
.toLowerCase()
.includes(i.toLowerCase())
)
);
});
My action.payload
has following values ["Red", "Blue", "Green"]
but it only filters out according to the last element in the array.
2
Answers
First, I am guessing that both payload and state.products are arrays.
You may want to initialize the
filterData
from outside theforEach
because most likely it is being overwritten on every loop hence filters out according to the last element in the arrayThat is correct since the current implementation loops over the payload and overwrites the
filterData
value, so the last iteration is the value that "sticks".If you are filtering
state.products
then this is the object that should be iterated on the outer loop, the payload array will be the inner-most loop.Example: