Skip to content
Advertisement

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

To do:

  • select 0 hr only show 15, 30, 45 minutes select
  • 1,2,3,4 hr show 0,15, 30, 45 minutes

I want to shorthen this if else statement

onHourChange(hours: number) {

if (hours === 0) {
 this.minuteOptions = [
  { value: 15, display: '15' },
  { value: 30, display: '30' },
  { value: 45, display: '45' },
 ]


} else if (hours === 1) {
  this.minuteOptions = [
    { value: 0, display: '00' },
    { value: 15, display: '15' },
    { value: 30, display: '30' },
    { value: 45, display: '45' },
  ];

}

Use this array to delete or remove from the array when the value 0 is selected

  ngOnInit() {
    this.hourOptions = [
      { value: 0, display: '0' },
      { value: 1, display: '1' },
      { value: 2, display: '2' },
      { value: 3, display: '3' },
      { value: 4, display: '4' },
    ];
    this.minuteOptions = [
      { value: 0, display: '00' },
      { value: 15, display: '15' },
      { value: 30, display: '30' },
      { value: 45, display: '45' },
    ];

Advertisement

Answer

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);
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement