Simplifying array item toggling using only vanilla JavaScript

Seeking feedback on how to further simplify the code snippet below or if this is the most efficient approach. The goal is to add action.payload to the roles array if it's not already included, and if it is present, remove it without using lodash.

const idx = state.rolesFilter.findIndex(
  role => role === action.payload,
);
if (idx === -1) {
  nextState.roles.push(action.payload);
} else {
  nextState.roles = state.roles.filter(role => role !== action.payload);
}

Answer №1

A good option is to utilize the Set method

const set = new Set(state.roles);
const action = set.has(action.payload) ? 'delete' : 'add';
set[action](action.payload);
nextState.roles = [...set]; 

If you anticipate using the "toggle" function frequently, consider creating a custom function

function toggle(array, item) {
    const set = new Set(array);
    const action = set.has(item) ? 'delete' : 'add';
    set[action](item);
    return [...set];
}

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

Converting a customer ShaderMaterial to Lambert Material using Three.js

Currently, I am utilizing a cell shading script to shade a Lambert material on a model. However, I am facing challenges when trying to apply the same script to a custom Shader Material. Is there a way to convert the custom material into a Lambert materia ...

Using Django to Send a POST Request with JavaScript

I'm currently facing an issue with a JavaScript event-triggered function that is supposed to send a POST request to update objects in my database. The function is triggered by a drop-event, which made me initially avoid using forms for the request. Ho ...

Using JQuery to switch out images that do not have an ID or class assigned

Currently, I am using a Google Chrome Extension to apply an external theme to a website. Unfortunately, the logo on the site does not have an ID or class that can be used to call it. I am searching for a solution to replace it with a different image. My ...

Prevent scale animation for a specific section of the icon using CSS

I need help in preventing the scale animation of the :before part of the icon class from occurring when the button is hovered. The current behavior is causing the arrow to look distorted on hover... Link to the code on Codepen HTML <div class="se ...

JavaScript module dependency management technique

Just starting out with JavaScript, I'm attempting to incorporate a JavaScript library/sdk. I've familiarized myself with common patterns and currently considering using the revealing module pattern. To provide a concrete example, let's imagi ...

Issue with deploying NEXT.JS due to a failure in the build process caused by next lint

Issue I have been encountering deployment failures on Vercel due to lint errors in test files within my git repository. Despite following the recommendations from the Vercel documentation for ESLint settings, the issue persists. According to Vercel' ...

Encountered a parsing issue while attempting to retrieve JSON data from an API in Dialogflow

I am currently working on retrieving JSON data from the iex API. Utilizing Google's Dialogflow inline editor, I encountered an error while attempting to fetch the JSON information: Error: Parse Error at Error (native) at Socket.socketOnData (_http_cl ...

Unexpected quirks in Canvg conversion: Strange behavior observed while utilizing a fill URL

I am attempting to use the canvg javascript library to convert an svg to canvas. Within the original svg, there is a rectangle with a fill attribute that references a svg pattern. However, when I convert the svg to canvas using canvg: canvg(document.getE ...

Issue with React Material-UI drawer not functioning properly when invoking a child component function from the parent

Here is a piece of code I have for the App.js file: import React, { Component } from 'react'; import logo from './logo.svg'; import './App.css'; import Child from './child'; class App extends Component { render() ...

Combining duplicate key-value pairs in a JSON object into an array using JavaScript

Is it possible to merge value objects with the same key but different values? For example, in this case, "field_template_id": 2 appears twice with different values. This is the original JSON data: { "id": "c2dec94f", "data": [ { "field_temp ...

Finding a specific string within a multidimensional array using PHP

Receiving an array from a server's response, it sometimes looks like this: $array = Array ( [0] => Message: Thanks for all [1] => Response: Goodbye [2] => [3] => inactive [4] => acti ...

What are the best methods for testing REST API and Client-side MVC applications?

When dealing with a RESTful server that only responds with JSON data fetched from a database, and having a client-side application like Backbone, Ember or Angular, where should application testing take place? Is it necessary to have two sets of tests - on ...

Safari's Web Audio API suffering from subpar performance and various shortcomings

For my University project, I am developing an HTML and JavaScript-based mp3 player using the Web Audio API. You can check out the progress of this project by visiting this link: While everything is running smoothly on Firefox and Chrome, Safari is posing ...

Selenium Webdriver encounters difficulty in retrieving the handle for JavaScript popup windows

I am facing an issue on one of my web pages where a button opens up a popup window that requires me to select certain values. I am using IE browser and Selenium 2.53 libraries for automation. However, I am unable to switch to this popup window as I can&apo ...

Upon the completion of the page loading, the function will be called immediately after the controller has provided the

I am facing an issue where I am trying to call a computed property upon page creation, but it is giving an error stating that it cannot read the data for 'undefined'. This is because the data I require is not fully loaded yet. However, when I del ...

"Integrating Prismic.io with Meteor js: A seamless way

Using THIS javascript developer kit from Prismic.io, I aim to fetch content into a meteor template. Initially, I am uncertain of the best approach, whether to construct my main meteor template with spacebars: {{title}} or utilize the predicate system fo ...

Storing the options' ids in an array within a select box using JavaScript: tips and tricks

Check out this snippet of HTML code: <select id="s1"> <option value="volvo" id="o1">Volvo</option> <option value="saab" id="o2">Saab</option> <option value="opel" id="o3">Opel</option> <option value="au ...

Exploring Vue3's defineprops feature in conjunction with v-model within a child component

It seems that directly changing the props value in a child component is not recommended, but I have discovered a way to do it successfully. I am curious about the reasoning behind this behavior. Just for context: I am working with vue3+vite For instance: ...

There are mistakes in the code that I am struggling to fix

I am encountering an issue where my website only functions properly on Firefox and not on Chrome. However, when I run the HTML using NetBeans on Chrome, the website works fine. I'm unsure of what to do as I need to submit this project within the next ...

Tips for encoding ParsedUrlQuery into a URL-friendly format

Switching from vanilla React to NextJS has brought about some changes for me. In the past, I used to access my URL query parameters (the segment after the ? in the URL) using the useSearchParams hook provided by react-router, which returned a URLSearchPara ...