skip to Main Content

I am trying to filter my array:

case ON_SET_RECENT_SEARCH: {
  const searchToSave = action.payload;


  const filteredSearches = state.recentSearches.filter(

    // function to check for duplicates - pass in current item and searchToSave to check against

    !checkForDuplicate(item, searchToSave),
  );


  return {
   ...
  };
}

checkForDuplicate function, console.log never gets called. How can I filter my array using my helper function?

const checkForDuplicate = (item, searchToSave) => {
  console.log('checkForDuplicate');
  const isDuplicate =
    (item.id === searchToSave.id &&
      item.fuelType === searchToSave.fuelType &&
      item.searchDistance === searchToSave.searchDistance) ||
    (!!item.isCurrentLocation && !!searchToSave.isCurrentLocation);

  return !isDuplicate;
};

2

Answers


  1. The parameter to .filter() should be an function like below.

    state.recentSearches.filter(item => !checkForDuplicate(item, searchToSave));
    
    Login or Signup to reply.
  2. The filter() method of Array instances receives a callback as the parameter and you were passing !checkForDuplicate(item, searchToSave) which is a value (the checkForDuplicate() is executed and returns a value before the filter() is executed). Just need to update it as

    state.recentSearches.filter((item) => !checkForDuplicate(item, searchToSave));
    

    Read more from the Array.prototype.filter() docs here

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search