4

I have order reducer, which has many states.

const initialState = {
 channel: null,
 order: {},
 fetching:true,
 menu: [],
 categories: [],
 subcategories: [],
 currentCategoryId: 1,
 currentSubcategoryId: 5,
 currentMenu: [],
};

What I want to filter is menu. menu is array of state which has objects of menu_item I have currentCategoryId and currentSubcategoryId. What I want to do with these states is that by using currentCategoryId and currentSubcategoryId to filter menu and put filtered states to currentMenu.

case Constants.ORDER_CHANNEL_CONNECTED:
 return
  {...state,currentMenu: action.menu.map((menu) => {
                    if(state.currentCategoryId == menu.category_id){
                        return menu;
                    }
                    else return false;}}

So to do that I made code like above. Even though it returns some filtered value, it shows same number of array with many false values. I want to find other approaches to do that..

How can I do this?

Thanks in advance.

4 Answers 4

14

Please use the filter function:

{...state,currentMenu: action.menu.filter((menu) =>
state.currentCategoryId == menu.category_id)}

P.S: I agree with the below answer, it's better to use Immutable.js

Sign up to request clarification or add additional context in comments.

2 Comments

why do you think that it is better to use Immutable.js?? any benefits compare to use just filter function?
Main reason to use immutable is to avoid expensive cloning whole object. Immutable object store only difference to the previous version. It works faster especially in the large project with big state objects. You can read more about benefits here
3

I would say you can use immutable.js for this purpose. You can add filter to your map.

You can try something like

Immutable.map(state.menu).filter(state.currentCategoryId===menu.category_id)

P.S: I have not tested the above code but it should work with little modifications.

You can check out more about immutable here

1 Comment

thanks, I tried currentMenu: Immutable.map(state.menu).filter(state.currentCategoryId===menu.category_id), but it triggers error that Immutable.map is not defined.. so I tried Immutable.Map(state.menu).... but it still triggers error that menu is not defined How should I change this?
2
onTodoClick(id){
      this.setState({items: this.state.items.filter(item => item.news_id == id )
      });
    }

Comments

2

If you are filtering by ID and it is numeric watch out for comparing strings and numbers. I had to use parseInt (as below).

Arr.filter(single => parseInt(single.id) !== parseInt(id))

Consider this if javascript filter array is not working

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.