Shashika Virajh
Shashika Virajh

Reputation: 9457

Removing exactly one item in js array

In my react native application, I have a scenario like this. There is an array, when we feed this array, same item can be in the array more than once.

[movement-one, movement-two, movement-three, movement-two, movement-two]

I want to remove only one movement-two, when executes the remove function with the id of movement-two in the reducer. But now, when I remove an item which is in the array more than once, it removes all the items related to the id. How can I remove only one item even though it duplicates in the array? This is my code.

  case REMOVE_MOVEMENT:
      return {
        ...state,
        selectedTrainerMovements: state.selectedTrainerMovements.filter(
          movement => {
            return movement.id !== action.movement.id;
            // return state.selectedTrainerMovements.splice(
            //   state.selectedTrainerMovements.indexOf(movement)
            // );
          },
          state.selectedTrainerMovements.indexOf(action.movement),
        )
      };
      break;

Upvotes: 0

Views: 69

Answers (1)

Kirill Glazunov
Kirill Glazunov

Reputation: 497

case REMOVE_MOVEMENT:
  let removed = false;

  return {
    ...state,
    selectedTrainerMovements: state.selectedTrainerMovements.filter(
      movement => {
        if (!removed && movement.id === action.movement.id) {
          removed = true;

          return false;
        }

        return true;
      }
    )
 };

Upvotes: 1

Related Questions