rick1
rick1

Reputation: 946

Filter redux store item array for duplicates

I have following reducer:

case INIT:
  return {
    ...state,
    items: [...state.items, ...action.payload],
  };

I need somehow to check if in state.items array are items from action.payload array and do not include them in state.items. I have such a code:

[...state.items.filter(item => item !== action.payload)],

but it doesn't what I need, it doesn't work. Can somebody help me?

Upvotes: 0

Views: 56

Answers (2)

str
str

Reputation: 44979

The easiest way to handle that with primitive types is using Set:

case INIT:
    return {
        ...state,
        items: [...new Set(state.items.concat(action.payload))],
    }

Upvotes: 2

Arup Rakshit
Arup Rakshit

Reputation: 118271

You should filter the payload.

case INIT:
      const { items } = state;
      const newItems = action.payload.filter(item => !items.includes(item))]
      return {
        ...state,
        items: items.concat(newItems),
      }

Upvotes: 0

Related Questions