Redux Reducer: Filter Out Duplicate Objects?

493 views Asked by At

I have a groceryReducer where I add groceryItems to. The format of each object that is added to the groceryItems array is listed below. I'm trying to use the newSet array method, but it's still adding them and not filtering out the duplicates. What am I doing wrong?

groceryObject

{
  title: "Chorizo Turkey Chili",
  subtitle: "Soup/Stew"
}

groceryReducer

// Action Type: Add Grocery Item
case 'ADD_GROCERY_ITEM': {

  return {
    ...state,
    groceryItems:  Array.from(new Set(state.groceryItems.concat(action.groceryObject))),

  }
}

console.log

groceryItems: Array(4)
  0: {title: "Chorizo Turkey Chili", subtitle: "Soup/Stew"}
  1: {title: "Chorizo Turkey Chili", subtitle: "Soup/Stew"}
  2: {title: "Chorizo Turkey Chili", subtitle: "Soup/Stew"}
  3: {title: "Chorizo Turkey Chili", subtitle: "Soup/Stew"}
1

There are 1 answers

0
Nick On BEST ANSWER

The Set object will keep unique references, it doesn't compare properties of an object.

One way you could accomplish this is creating a set of titles and comparing those.

case 'ADD_GROCERY_ITEM': {
  const titles = new Set(state.groceryItems.map(item => item.title));
  if (titles.has(action.groceryObject.title)) {
    // Already exists in state, don't add
    return state;
  }
  // doesn't exist in state, add it!
  return {
    ...state,
    groceryItems: state.groceryItems.concat(action.groceryObject)
  }
}