skip to Main Content

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


  1. First, I am guessing that both payload and state.products are arrays.
    You may want to initialize the filterData from outside the forEach because most likely it is being overwritten on every loop hence filters out according to the last element in the array

    
    const searchParameters = data && Object.keys(Object.assign({}, ...data));
    let filterData = state.products;
    
    action.payload.forEach((i) => {
       filterData = filterData.filter((item) =>
         searchParameters.some((parameter) =>
           item[parameter]
             .toString()
             .toLowerCase()
             .includes(i.toLowerCase())
        )
      );
    });
    
    Login or Signup to reply.
  2. My action.payload has following values ["Red", "Blue", "Green"]
    but it only filters out according to the last element in the array.

    That 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:

    const searchParameters = data && Object.keys(Object.assign({}, ...data));
    
    const colors = action.payload.map(val => val.toLowerCase());
    
    const getItemParam = (item, parameter) =>
      (item[parameter] ?? "").toString().toLowerCase();
    
    const filterData = state.products.filter(item => {
      return searchParameter.some(parameter => {
        const itemParam = getItemParam(item, parameter);
        return colors.some(color => itemParam.includes(color));
      });
    });
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search