Steps to delete an element from an array using an if-else statement

Task:

  • If the selected hour is 0, only display options for 15, 30, and 45 minutes.
  • For hours 1, 2, 3, or 4, show options for 0, 15, 30, and 45 minutes.

I am looking to simplify this conditional 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' },
  ];

}

Utilize this array to remove elements 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' },
    ];

Answer №1

One can explore various approaches for deleting an element from an array.

Displayed below is a snippet showcasing examples utilizing the filter, slice, and splice array methods to remove 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);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Create a boundary on a three-dimensional design that follows the shape of its exterior

I am in the process of developing a tool using Three.js to annotate three-dimensional models. My goal is to enable users to draw lines on a model that accurately follow its surface contours. For instance, when drawing a line on a face model, the line shoul ...

What is the best way to extract the image url from a page in WordPress?

Is there a way to extract the image URL in WordPress dynamically for use as a reference in a script? When I use postimage(); it extracts this: <a href="address"> <img width="300" height="300" src="image.png" class="image" alt="" title="LINKING"/& ...

Creating a wrapper for methods of a third-party class in TypeScript

I have been working on creating a wrapper for all my third party API interfaces and SDKs that logs requests in a standardized yet customizable way. My approach involves passing the third party API (typically instantiated with a new API() call) into a wrapp ...

Only carry out a redirect to the specified page if the successRedirect is present in the passport.authenticate function

Encountering some difficulties with a Node Express app. After removing the successRedirect property in the auth method by passport, it fails to redirect. The below code does not redirect to the desired page when the successRedirect is removed and replaced ...

`Why won't the checkbox uncheck when the dropdown is changed in jQuery?`

I have a roster of users, each with a unique checkbox for selection. When I adjust the dropdown menu, a new group of users is chosen and marked as selected. However, I am struggling to uncheck the previously selected checkboxes based on the last dropdown c ...

Issue with Backbone collection not being updated despite making a JSONP request

Recently, I delved into the world of Backbone.js and currently, I am immersed in developing an app using Brunch that makes a JSONP request to an external API for populating my collection and models. Despite following guidance from previous posts (here and ...

Using Vue to fetch JSON data with Axios

When trying to retrieve user data from a MongoDB in JSON format using axios.get within a Vue.js application, my aim is to visualize this data by iterating through all user objects in the users array. The issue I'm facing is that each character is trea ...

Creating a Fixed HeaderToolbar in FullCalendar React

I am currently working on customizing the FullCalendar React component and I am looking to incorporate a sticky headerToolbar. My main objective is to have the header along with its toolbar remain fixed at the top of the calendar, even when users scroll th ...

Instructions on how to retrieve all store items while filtering in React JS and Redux

I am encountering an issue while trying to implement a "typeahead" functionality in my application. I have an "input" that listens for onChange events, and when an onchange occurs, it calls a Redux reducer that searches for a tag in the entire store. Every ...

Tips for resolving a jspdf naming collision situation

In my react app, I am utilizing various jsPDF libraries as shown below: For exporting tables as HTML: import jsPDF from 'jspdf'; import "jspdf-autotable"; For converting SVG to PDF: const svg2pdf = require('svg2pdf.js'); con ...

Ways to extract particular keys from a JSON array?

I am receiving an array of JSON objects in my response. {"took":0,"timed_out":false,"_shards":{"total":1,"successful":1,"skipped":0,"failed":0},"hits":{"total":{" ...

Is it possible to utilize the inputted value from ng-model to populate an Angular ng grid?

This plunker successfully populates a static HTML Table with data related to the search term 'Tim' from JSON Data. var arrItem = []; angular.forEach($scope.items, function (item) { if(item.fname === enteredValue.firstName || item.lna ...

Error encountered when running shell command in JavaScript due to permission denial

I've been working on a JavaScript code to execute a shell command and open Notepad. Below is my current implementation: <script type="text/javascript"> function runNotepad() { var oShell = new ActiveXObject("Shell.Application"); ...

Drag and drop to upload files

Is there a way to enable drag-and-drop functionality for uploading and downloading files between a user's computer and web browser? If so, what is the best approach - ASP.NET with AJAX or JS/JQuery? ...

Internationalization of deferred-loaded modules within the JHipster application

I created My App using JHipster, which utilizes the JhiLanguageService in the ng-jhipster library. This service relies on the JhiConfigService to configure ngx-translate without requiring manual imports and configuration of the TranslateModule in my app.mo ...

reCAPTCHA using AJAX verification consistently gives incorrect results even when the input is correct

Take a look at this live example: When you fill out the form and enter all the necessary fields, if you input a correct or incorrect captcha, it shows as invalid. I've gone through everything I can think of and compared it to - but I can't seem ...

Puppeteer: Easily choosing a dropdown selection by its displayed text

When using Puppeteer, you have the ability to choose an option from a dropdown by specifying the value as a parameter: page.select('select#idOfSelect', 'optionValue'); I'm wondering if there is a way to select an option by its te ...

Suggestions for resetting the input field IDs in a cloned div after deletion

In the given HTML code snippet, there is a <div> containing two input fields as shown below: <button type = "button" id = "add-botton" >Add Element </button> <div id = "trace-div1" class = "trace"> <h4><span>Trac ...

What is the method for utilizing Jquery to target the width value of an inline property?

I am struggling with selecting the "style=:width: 10%" value using jquery for a progress bar element in bootstrap. <div class="progress-bar progress-bar-info" role="progressbar" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100" style="width: 10% ...

I am currently facing a problem with the PrimeNG calendar feature that is causing issues with setting the minimum date for December and disabling the minimum year

click here to view image The PrimeNG calendar component is presenting a challenge with the minimum date setting for December 2nd to 31st. It seems to be malfunctioning, causing the minimum year to become disabled. Additionally, when the maxdate is set to ...