JavaScript: Add element to array if it doesn't already exist, or remove it if it does

How can we efficiently toggle an element in an array using TypeScript?

By toggling, I mean:

  • If the element is already present, remove it.
  • If the element is not present, add it.

We are looking for a solution that minimizes computational effort.

Answer №1

Here is a typesafe method that can be used to toggle a value within an array without mutating the original array.

const toggleValue = <T extends unknown>(arr: Array<T>, val: T) => {
  const newArr = arr.filter((item) => item !== val)
  if (newArr.length === arr.length) return arr.concat(val)
  return newArr
}

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

Is it possible to retrieve data using a POST request?

An organization has assigned me an Angular task. They have given the following guidelines, however, the API URL is not functioning: Develop a single-page Angular application using the provided API to fetch sports results and organize them in a displayed ta ...

Determine whether the radio button has been selected

Within my HTML code, there's a radio button enclosed in a form: <mat-radio-button [(ngModel)]="boxChecked" name="boxChecked" value="boxChecked">Check me</mat-radio-button> In the TypeScript section, I've declared my boolean variable ...

Ionic/Angular 2: Issue accessing object in the Page1 class - error caused by: Unable to retrieve the 'name' property as it is undefined

Currently, I am working on developing an application using Ionic and below is the code snippet: <ion-header> <ion-navbar> <button ion-button menuToggle> <ion-icon name="menu"></ion-icon> </button> &l ...

Creating an ArrayList in Java and invoking a method within the class

I have been working on creating an ArrayList of objects that all have the same method which I need to call in the order they appear in the ArrayList. My current code looks like this: public class Shape extends Application { public void do(GraphicsCon ...

Leveraging Async/Await in NodeJS within Array.map alongside an 'if' condition

Within my code, there is a recursive function that iterates over an object. It specifically searches for keys labeled subcomponent (always containing an array) and executes an asynchronous task on each child within subcomponent, using the output to replace ...

initiating nest start removes the json files in the dist directory

As I work on my nestjs application, I find myself needing to ensure that specific json files are copied to the dist directory. This is especially important for the "engines" folder, where the json files in src/engines must be replicated in dist/and prod. ...

What is the proper way to invoke a child method after converting an object from a parent class to a child class?

When we have a subclass B that overrides a method from its superclass A in TypeScript, why does calling the method on an instance of A result in the parent class's implementation being called? In TypeScript, consider a class called Drug with properti ...

Trouble parsing JSON in Classic ASP

After receiving a JSON Response from a remote server, everything looks good. I discovered an helpful script for parsing the JSON data and extracting the necessary values. When attempting to pass the variable into JSON.parse(), I encountered an error which ...

A guide on leveraging Vue class components alongside the composition API in Vue2 using TypeScript

<script lang="ts"> import { Component, Vue } from 'vue-property-decorator' import { CustomerContext, getCustomerRepository } from '@/composables/customerRepository' @Component export default class CustomerList extends V ...

Mastering the art of linking together recursive Ajax load promises in TypeScript

I'm making an effort to adhere to good jQuery practices and utilize promises, but I still struggle with some basic concepts. Below is a panel loading method that might need to redirect to another page instead of loading the originally specified one. ...

Using the jQuery .each() method to generate an array of objects

I have a goal of creating something similar to this. var data = google.visualization.arrayToDataTable([ ['Year', 'Cost'], ['2004', 1000], ['2005', 1170], ['2006', 660], ['2007&a ...

Organize values in a flat array by repeatedly using a flat array of keys

I have an array of values: $values = [1,2,3,4,5,6,7,8,9,10,11,12]; As well as another array containing keys, but it may not always be long enough to match up with the values. $keys = ['itema', 'itemb', 'itemc', 'itemd&ap ...

Navigating through React with Typescript often involves managing the process of waiting for an API call to finish

My interface structure is as follows: export interface Chapter{ id: string, code: string } Within a component, I am making an API call in the following manner: componentDidMount() { fetch("https://someapi/getchapter") .then(r ...

Experiment with Observable in fakeAsync, applying a delay and tick functions through Jasmine testing framework

I am currently working with a pipe that assists in returning the state of an observable. import {Pipe, PipeTransform} from '@angular/core'; import {Observable, of} from 'rxjs'; import {catchError, map, startWith} from 'rxjs/operato ...

By implementing set_userdata() in CodeIgniter, the existing session value is updated with the new value

Currently facing an issue with merging previous session values with current session values. Unfortunately, when trying to merge both values, the last session gets destroyed. Below is the code I am using to merge session arrays: $sess=$this->session-&g ...

Utilizing Object Arrays in Chart.js for Optimal Performance

I'm struggling with using chart.js to create charts for my admin panel. I'm having trouble figuring out how to properly utilize my JSON array of objects in order to generate the correct dataset. What exactly should I be putting in the data field ...

Retrieving data from an array with knockout.js

I have a function that receives an array and I want to extract the information from it to display on the page. Here is how the array is structured: EducationalClasses: [object, object] The first object contains: classId: "324342", className: ...

Prevent the array from altering its values

I am utilizing a mock-service that is configured in the following way: import { Article } from "./article"; export const ARTICLES: Article[] = [ new Article( 1, 'used', 5060639120949, 'Monster Energy& ...

Is there a way for me to retrieve the identifier of a boolean variable instead of its actual value?

Just beginning my coding journey with JavaScript and struggling to find a simple solution through online searches. I'm attempting to locate a JavaScript function or similar method that can identify the name of a boolean in an array (not just its valu ...

How can you activate a checkbox by simply clicking anywhere on the row?

I am working with a list of checkboxes and currently, the user can only activate a checkbox by clicking directly on the checkbox itself. Is there a way to allow users to activate a checkbox by clicking anywhere in the same row as the checkbox? return( ...