Using the splice method on an array is only effective when done in a specific sequence

I've encountered a small issue. I have checkboxes that correspond to different divs, and when checked, the name of the div is sent to the server. However, when unchecking the checkboxes in a specific order, the array doesn't update correctly.

 $scope.savesGraphUserDetail = [];
    $scope.addRemoveUserChart = function(checked, value) {
      if (checked) {
        $scope.savesGraphUserDetail.push(value);

        var config = { headers: { "Content-Type": "application/x-www-form-urlencoded", "X-HTTP-Method-Override": "PUT" } };
        var data = {graphsConfig: $scope.savesGraphUserDetail};

        $http
        .post(serviceBase + "blabla", data, config)
          .success(function(data, status, headers, config) {
          })
          .error(function(data, status, header, config) {
          });
      }else {
        var index = $scope.savesGraphUserDetail.indexOf(value);
        $scope.savesGraphUserDetail.splice(index);

        var config = { headers: { "Content-Type": "application/x-www-form-urlencoded", "X-HTTP-Method-Override": "PUT" } };
        var data = {graphsConfig: $scope.savesGraphUserDetail};

        $http
          .post(serviceBase + "blabla", data, config)
          .success(function(data, status, headers, config) {
          })
          .error(function(data, status, header, config) {
          });
      }

The problem arises when unchecking checkboxes in an inconsistent order. The array does not remove only the unchecked item as intended, resulting in unexpected behavior. How can this be fixed?

Answer №1

To effectively use the deleteCount parameter of Array#splice, it is important to specify its value. Without specifying the deleteCount, all elements from the actual index will be deleted.

Parameters

deleteCount Optional

This parameter should be an integer that indicates the number of old array elements to remove. If the deleteCount is set to 0, no elements will be removed. In such cases, it is necessary to specify at least one new element. If the deleteCount exceeds the number of elements in the array starting from the specified index, all remaining elements until the end of the array will be deleted.

If the deleteCount is not provided or if its value is greater than the difference between the length of the array and the start index, then all elements from the specified index to the end of the array will be deleted.

$scope.savesGraphUserDetail.splice(index, 1);
//                                        ^

Answer №2

The issue you're facing is due to the fact that you're using the .splice() function with only the index parameter. You should include 1 as the second parameter, specifying the number of items to be spliced, with the optional deleteCount.

var index = $scope.items.indexOf(value);
$scope.items.splice(index, 1);

If you omit the second parameter, all elements from the start index to the end of the array will be removed, explaining why "C" and "D" were also deleted in your attempt.

Further Reading:

To learn more about the correct usage of the .splice() method, refer to the documentation on MDN:

https://i.sstatic.net/tDBfw.png

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

How to designate a try / catch block as asynchronous in TypeScript / JavaScript?

I am facing an issue where the code is not entering the catch block in case of an error, try { this.doSomething(); } catch (error) { console.error(error); } This problem occurs when "doSomething" returns a promise or runs asynchronous code. doSome ...

Is there a way to verify an email address and transfer form data to a different HTML page for printing?

How do I troubleshoot email validity checking issues in my form? It works fine when no characters are entered, but fails when characters are inputted. What could be causing this problem? Additionally, I want to open a new HTML sub-file after form submissi ...

PHP WebService, exclusively containing private variables within an empty array

I'm attempting to create a PHP webservice. In the "Aluno" class, there are 2 private variables. After struggling all day with this, I finally discovered that if I change those variables to public, everything works as expected. However, if they remain ...

What is the best way to personalize Material UI elements, such as getting rid of the blue outline on the Select component?

Embarking on my journey of developing a React app, I made the decision to incorporate Material UI for its array of pre-built components. However, delving into the customization of these components and their styles has proven to be quite challenging for me ...

When utilised within the same function, JSON values in JavaScript can yield varying results

Recently, I've been grappling with a JavaScript issue that involves fetching JSON values as data-attributes to populate a modal. This task sounds simple enough, but as a newcomer to this field, I find myself facing challenges. The main goal is to ite ...

What is the most straightforward AngularJs 'Hello World' example you would use when introducing AngularJs to a newcomer?

Can someone provide a beginner-friendly 'Hello World' example in AngularJS? I'm trying to learn and so far have come up with this: <!DOCTYPE html> <html> <head> </head> <body> <div data-ng-app=""> ...

Creating flexible items with a 1:1 ratio and ensuring that the padding on the left and right of the flex container remains consistent

Whenever I adjust the size of the window, https://i.sstatic.net/Fm3d1.png the flex-container ends up with uneven padding on the left and right, which is less than ideal. So, I am looking for a way to allow the flex-item to resize when the window size c ...

Using Jquery to handle input data in a form

Using jQuery, I have set up an AJAX function to fetch data from a database in real-time as the user fills out a form with 5 input fields. Currently, my code looks like this: $("#searchtype, #searchtext, #searchtag, #daterangefrom, #daterangeto").on("load ...

Is it possible to exclusively focus on the specified data attributes?

Is there a method to specifically target the 'data-season' attribute with the value "winter"? This is my HTML: <li data-season="summer">summer <ul class="groups"> <li data-item="beach">beach</li> <li data-item ...

Turn the image inside the div with the nth-child selector into a clickable link

I'm currently facing a challenge on my Squarespace website where I need to add individual links to various images using jQuery. The issue is that these images do not have a shared class, and unfortunately, I am limited to adding custom CSS or JavaScri ...

I require the ability to retrieve only the data from a UI grid column, specifically based on the column name selected

I need help with my angularjs application that utilizes Ui grid. There is an external dropdown menu located outside of the ui grid, which lists all the column names in the grid. I want to be able to select a specific column name from this dropdown and retr ...

Guide on redirecting to a specific tab data target in Symfony 5

When a user is on the 3rd tab and clicks on a DELETE button, I want to redirect the user back to the same 3rd tab on the page. **Template:** <nav> <ul class="nav nav-tabs"> <li class="nav-item"> ...

Angular date filter: Display month in the current time zone format

My date is in ISO-8601 format: overview.startTime = "2017-05-09T08:00:00Z" I am trying to display it on my webpage using the code below: Dagens arbetspass {{overview.startTime | date:'dd-MMM'}} However, the output shows "Dagens arbetspass 09-M ...

Enhancing the Rendering of React's props.children

I have set up my code like this: // Parent.js class Parent extends React.Component { render() { return { this.props.children } } } // Child.js class Child extends React.Component { render() { let message; const greet = ...

Error Message: Unable to access properties of an undefined object while interacting with an API in a React application

Creating a Weather application in React JS that utilizes the OpenWeatherMapAPI to display dynamic backgrounds based on the API response. I need to access the data at 'data.weather[0].main' which will contain values like 'Clear', ' ...

Unable to connect to React Node Socket.IO application from any source other than localhost using IPv4 and NGROK

I recently followed a tutorial on creating a simple React app/Node with Socket.IO. The tutorial worked perfectly, so I decided to test it with two other devices: One PC on the same wifi network (via IPv4 - 192.168.1.8:3000) A mobile device using Ngrok tun ...

Can the combination of pure HTML+JS applications with .NET webservices be both feasible and safe?

Our recent projects have utilized MVC5 with AngularJS, Ninject, Bootstrap, and various other technologies. However, we found that these applications required significant time to fix bugs and add features due to unnecessary complexity. Would it be feasible ...

Error Found: Syntax Error - 'if' statement not recognized

if (fname == null || fname == "") { Receiving an error message "uncaught syntax error:unexpected token if in line 13". The error indicates "SyntaxError: missing variable name" when using Javascript lint function validateRegistration() { var emailReg ...

Steps to implement an image zoom function triggered by a button click

I'm working on a school project that requires me to use only html, css, and javascript for creating a website. Currently, I'm designing a landing page with a button that will navigate the user to another page. My goal is to have the background im ...

Tips for using a button to update data without triggering a postback

Within the GridView in my ASP.net project, I have an ASP.net button with the following code: <asp:Button UseSubmitBehavior="false" runat="server" ID="btnShow" CssClass="btnSearch" Text="View All" CommandName="ViewAll" OnCommand="btnShow_Command" Comman ...