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
JavaScript
x
20
20
1
onHourChange(hours: number) {
2
3
if (hours === 0) {
4
this.minuteOptions = [
5
{ value: 15, display: '15' },
6
{ value: 30, display: '30' },
7
{ value: 45, display: '45' },
8
]
9
10
11
} else if (hours === 1) {
12
this.minuteOptions = [
13
{ value: 0, display: '00' },
14
{ value: 15, display: '15' },
15
{ value: 30, display: '30' },
16
{ value: 45, display: '45' },
17
];
18
19
}
20
Use this array to delete or remove from the array when the value 0 is selected
JavaScript
1
15
15
1
ngOnInit() {
2
this.hourOptions = [
3
{ value: 0, display: '0' },
4
{ value: 1, display: '1' },
5
{ value: 2, display: '2' },
6
{ value: 3, display: '3' },
7
{ value: 4, display: '4' },
8
];
9
this.minuteOptions = [
10
{ value: 0, display: '00' },
11
{ value: 15, display: '15' },
12
{ value: 30, display: '30' },
13
{ value: 45, display: '45' },
14
];
15
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.
JavaScript
1
51
51
1
class TimeFilter {
2
onHourChange(hours) {
3
const noZeroMinutes = item => !(hours === 0 && item.value === 0);
4
5
this.minuteOptions = [
6
{ value: 0, display: '0' },
7
{ value: 15, display: '15' },
8
{ value: 30, display: '30' },
9
{ value: 45, display: '45' },
10
].filter(noZeroMinutes); // filter the elements that have 0 minute and 0 hours
11
}
12
}
13
14
class TimeSlice {
15
onHourChange(hours) {
16
this.minuteOptions = [
17
{ value: 0, display: '0' },
18
{ value: 15, display: '15' },
19
{ value: 30, display: '30' },
20
{ value: 45, display: '45' },
21
];
22
23
if (hours === 0) {
24
this.minuteOptions = this.minuteOptions.slice(1); // remove first element from the array
25
}
26
}
27
}
28
29
class TimeSplice {
30
onHourChange(hours) {
31
this.minuteOptions = [
32
{ value: 0, display: '0' },
33
{ value: 15, display: '15' },
34
{ value: 30, display: '30' },
35
{ value: 45, display: '45' },
36
];
37
38
if (hours === 0) {
39
this.minuteOptions.splice(0, 1); // remove first element from the array
40
}
41
}
42
}
43
44
const time = new TimeFilter();
45
// const time = new TimeSlice();
46
// const time = new TimeSplice();
47
48
time.onHourChange(0);
49
console.log(time.minuteOptions);
50
time.onHourChange(5);
51
console.log(time.minuteOptions);