[Solved] How to remove an item in an array in if else statement [closed]


There are many options how you can delete an element from the array.

Look at the snippet below, there you can find examples with filter, slice and splice array methods for removing items.

class TimeFilter {
  onHourChange(hours) {
    const noZeroMinutes = item => !(hours === 0 && item.value === 0);
    
    this.minuteOptions = [
      { value: 0, display: '0' },
      { value: 15, display: '15' },
      { value: 30, display: '30' },
      { value: 45, display: '45' },
    ].filter(noZeroMinutes); // filter the elements that have 0 minute and 0 hours
  }
}

class TimeSlice {
  onHourChange(hours) {
    this.minuteOptions = [
      { value: 0, display: '0' },
      { value: 15, display: '15' },
      { value: 30, display: '30' },
      { value: 45, display: '45' },
    ];
    
    if (hours === 0) {
      this.minuteOptions = this.minuteOptions.slice(1); // remove first element from the array
    }
  }
}

class TimeSplice {
  onHourChange(hours) {
    this.minuteOptions = [
      { value: 0, display: '0' },
      { value: 15, display: '15' },
      { value: 30, display: '30' },
      { value: 45, display: '45' },
    ];
    
    if (hours === 0) {
      this.minuteOptions.splice(0, 1); // remove first element from the array
    }
  }
}

const time = new TimeFilter();
// const time = new TimeSlice();
// const time = new TimeSplice();

time.onHourChange(0);
console.log(time.minuteOptions);
time.onHourChange(5);
console.log(time.minuteOptions);

0

solved How to remove an item in an array in if else statement [closed]