An array that has been spliced in JavaScript may exhibit irregular behavior

Looking for help with splicing an array upon clicking an element. The issue is that the new array seems irregular, sometimes removing the wrong element or not removing the last index. Any insights on what might be causing this?

var container = document.getElementById('container'),
notDone = document.getElementsByClassName('notDone'),
deleting = document.getElementsByClassName('delete'),
div,
remove,
i,
toDo = [
'One',
'Two',
'öäå'],


for(i = 0; i < toDo.length; i++){
    div = document.createElement('div');
    div.innerHTML = toDo[i];
    div.className = 'notDone';
    remove = document.createElement('div');
    remove.innerHTML = '<p>Remove</p>';
    remove.setAttribute("data-id", i);
    remove.className = 'delete';

    container.appendChild(div);
    div.appendChild(remove);

    notDone[i].addEventListener('click', function(){

        if(this.classList.contains('notDone')){
            this.className = 'done';
        }else{
            this.className = 'notDone';
        }
    });

    deleting[i].addEventListener('click', function(event){
        event.stopPropagation();
        var shouldDelete = this.getAttribute("data-id");
        console.log('va' + shouldDelete);
        toDo.splice(shouldDelete, 1);
        this.parentNode.remove();
        console.log(toDo);
    });
}
var check = document.getElementById('check');
check.addEventListener('click', function(){
    console.log(toDo + ' checking array')
});

Answer №1

Occasionally, the incorrect array element is removed.

The issue you are encountering stems from the fact that the data-id stores a static index while the toDo array is changeable. When you delete an element from the array, all subsequent indices become invalid. For example, if you use .splice(0, 1), you will no longer be able to execute

splice(2, 1)</code because there are only two items remaining in the array.</p>

<blockquote>
  <p>The final index never gets removed.</p>
</blockquote>

<p>It would have been removed if you had initially clicked on the last element.</p>

<hr>

<p>Instead of removing indices from the <code>toDo
array (essentially truncating it), consider either:

  • Keeping the toDo array intact and simply setting the values to null; or
  • Storing the values you wish to remove rather than their original indices, and then searching for them using indexOf each time you want to remove an element.

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

Troubleshooting React hooks: Child component dispatches not triggering updates in parent component

I've been trying to implement a method of passing down a reducer to child components using useContext. However, I encountered an issue where dispatching from a child component did not trigger a re-render in the parent component. Although the state ap ...

What are the steps to utilize the feature of "nprogress"?

After successfully installing npm install nprogress in my project, I encountered an issue when trying to refresh the page - the console displayed the following message: hot-dev-client.js:182 [Fast Refresh] done hot-dev-client.js:196 [Fast Refresh] rebuildi ...

Modifying letter casing in Java with the input of "CAPS"

i am looking to create a program that takes an integer input representing the number of strings of characters to be entered, including CAPS. I want the program to change the characters following each CAPS input to either upper or lower case (default is low ...

Sudden slowdown due to Jquery error

I am encountering an issue with the Jquery registration validation. I am struggling to display the error message if a name is not filled in. jQuery(document).ready(function () { $('#register').submit(function () { var action = $(thi ...

Implementing automatic updates for Vue.js model data from a global object

I'm new to working with Vuejs and I'm encountering an issue with updating data from a global object automatically. My project involves the use of ES6 and Vuejs. The problem I'm facing is related to enabling/disabling a button based on a glo ...

Tips for eliminating the apostrophes in the request header of a Node.js application

Just a simple header object, that's all I have. let headers = { "pragma": "no-cache", "upgrade-insecure-requests": 1 } Using this header object with request-promise in node.js causes a timeout when sending a request to the web url. However, if ...

AngularJS function for alternating addition and subtraction operations

I am looking to create a toggle button that will add money to a total price when clicked once, and subtract that amount when clicked again to "deselect" it. Currently, I have this HTML code that toggles between adding and removing a class to change the ba ...

Utilizing .trigger repeatedly within a loop

I am in search of a solution to iterate through items in a select box, checking if any of them already have quantity data saved in the API, and then appending those items to the page. My current code achieves this by using .trigger('change'), bu ...

Navigating to User's Specific Info Page using Node.js

Would love some input on my current issue. I have a table featuring a list of users, and my goal is to display user information in detail whenever a user (which corresponds to a row in the table) is clicked. The process involves identifying which user was ...

When passing parameters through a URL in TypeScript, the display shows up as "[object object]" rather than as a string

Hey there! I'm trying to pass some string parameters to my URL to fetch information from an API. Everything seems fine, and when displayed in an alert, the URL looks exactly as it should (no [object, object] issue). var startDate = "2020-09-20"; var ...

Obtaining a pointer using a pointer to a constant value

I need to populate an array with literals using only the address of the array. My current approach involves creating a local array, filling it with the desired values, and then copying the content to the final destination array. Here's an illustration ...

Access the Express server by connecting to its IP address

Is it feasible to connect to an express server using the server's UP address? If so, how would one go about doing this? (Examples of code snippets would be greatly appreciated) ...

Implement generics within the `setState` function in a React.js and TypeScript application to ensure that it returns a string value

I'm facing an issue with setting the state in the onChange event by specifying the type of the setState hook. Here is my current setState declaration: const [payer, setPayer] = useState<Number>(0); And this is the radio setter function I am usi ...

How can I save files to the ~/Documents directory using Node.js on my Mac computer?

Trying to work with the user's Documents folder in Node.js on macOS: var logger = fs.createWriteStream('~/Documents/somefolderwhichexists/'+title+'.txt'); Encountering an error without clear cause. Error message received: Unca ...

Generate visual at reduced quality (three.js)

Is there a way to reduce the resolution of my rendered canvas similar to how it can be done with the Blender camera resolution? I came across a suggestion to use renderer.setDevicePixelRatio(window.devicePixelRatio) However, when I tried this, the objec ...

How do callback functions in Javascript interact with variables outside of their scope?

Greetings to all. I am facing an issue regarding the 'callback function - scope of variable', My intention is to utilize the 'i in for loop' with the 'callback function User_UidSearch', however, I am unable to implement it. ...

An error occurred during the bundling process in React Native

I recently started using react-native and encountered a perplexing error that I cannot quite figure out. My goal is to integrate a calendar library into my project: https://github.com/wix/react-native-calendars I have added the necessary dependency for t ...

Adding two-dimensional arrays in JNI

After facing challenges with Android Studio when working with NDK, I decided to switch to Eclipse for a smoother JNI and NDK development experience. However, even in Eclipse, I am struggling to make my project work. Can someone assist me? I started by cre ...

Ideal location to detect web browser and display or conceal a division

I am looking to display a div using either the ng-if or ng-show/hide directives if the user accesses the page through a specific browser, such as Chrome/Chromium. However, I am unsure of the optimal location to place this functionality. The JavaScript cod ...

The passport local strategy functions properly when tested with Postman, but encounters a "missing credentials" error when used with axios

I am currently working on creating a login system using passport and a local strategy. Strangely, when I attempt to send the request through axios it doesn't seem to work, although it functions properly with Postman. When using axios, I receive an er ...