skip to Main Content

I often have to check if an item is part of an array. If it is, I would like to remove it. If it’s not, then it should be added. Essentially its toggling the existence of a given item in the array.

const onDateSelected = function (date) {
  const inArray = selectedDates.value.find((d) => d === date) !== undefined;
  if (inArray) {
    selectedDates = selectedDates.filter((d) => d !== date);
  } else {
    selectedDates.push(date);
  }
};

Is there a shorter / quicker way to do this?

2

Answers


  1. You can try this :

    const onDateSelected = function(date) {
      const index = selectedDates.indexOf(date);
      index !== -1 ? selectedDates.splice(index, 1) : selectedDates.push(date);
    };
    
    Login or Signup to reply.
  2. Using a Set makes this a lot easier using has, delete and add:

    const data =  new Set([ 'foo', 'bar', 'foobar' ]);
    const removeOrAdd = 'bar';
    
    if (data.has(removeOrAdd)) {
        data.delete(removeOrAdd)
    } else {
        data.add(removeOrAdd)
    }
    
    console.log([...data]);

    If you really need an array, consider using indexOf combined with splice

    const data = [ 'foo', 'bar', 'foobar' ];
    const removeOrAdd = 'bar';
    
    const possibleIndex = data.indexOf(removeOrAdd);
    
    if (possibleIndex > -1) {
        data.splice(possibleIndex, 1);
    } else {
        data.push(removeOrAdd);
    }
    
    console.log(data);
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search