What is the best approach to eliminate an element from the array cart using JavaScript?

I currently have an array:

[
   0: {title: "Banana", price: 1.00, count: 2},
   1: {title: "Taco", price: 3.99, count: 1},
   2: {title: "Burrito", price: 6.50, count: 1},
   3: {title: "Soda", price: 1.25, count: 1},
]

which I display using the following code snippet:

var dataItems = "";
    for (i = 0; i < itemsArray.length; i++){
    var rand = Math.floor(Math.random()*1000)+1;
        dataItems += "<div id='"+rand+"' class='row pb-3 mx-3 mt-3' style='border-bottom:1px solid #eeeeee;'>";
        dataItems += "<div id='fs-7' class='col-2 text-center font-weight-bold quant'>";
        dataItems += itemsArray[i].count+"x";
        dataItems += "</div>";
        dataItems += "<div id='fs-7' class='col-5'>";
        dataItems += itemsArray[i].title+" "+i;
        dataItems += "</div>";
        dataItems += "<div class='col-3 pricep font-weight-bold text-right' style='color:#27c727;' id='price-item'>";
        dataItems += parseFloat(itemsArray[i].price).toFixed(2).toLocaleString()+" €";
        dataItems += "</div>";
        dataItems += "<div onclick='removeItem("+i+")' class='col-2'><img src='delete.png' style='max-height:20px;' class='img-fluid' /></div>";
        dataItems += "</div>";
    }

    $("#list-items").html(dataItems);

In the removeItem function:

function removeItem(item){
   itemsArray.splice(item,1);
}

However, when I delete an item, the position numbers of the remaining items do not update accordingly. How can I dynamically adjust and refresh the position numbers after removing an element?

Currently, my list looks like this:

2x Banana 1.00€ delete (position 0)
1x Taco 3.99€ delete (position 1)
1x Burrito 6.50€ delete (position 2)
1x Soda 1.25€ delete (position 3)

If I remove Banana, the list would appear as follows:

1x Taco 3.99€ delete (position 1)
1x Burrito 6.50€ delete (position 2)
1x Soda 1.25€ delete (position 3)

Answer №1

To remove the item from the array, simply set its value to undefined using this code snippet...

function removeItem(item){
   myArray[myArray.indexOf(item)]=undefined ;
}

Answer №2

In order to arrange items in an Array based on their position, the following code can be used.

const container = document.querySelector('#list');
const containerChanged = document.querySelector('#list2');

const appuntiFilter = [{
    title: "Banana",
    price: 1.00,
    count: 1
  },
  {
    title: "Pasta",
    price: 3.50,
    count: 1
  },
  {
    title: "Salad",
    price: 2.75,
    count: 1
  },
  {
    title: "Water",
    price: 0.79,
    count: 1
  },
];

// Display list
appuntiFilter.forEach((el, idx) => {
  const div = document.createElement('div');
  div.textContent = `${el.title}, ${idx}`;
  container.appendChild(div);
})

// Remove first item.
appuntiFilter.splice(0,1);

// Show updated list.
appuntiFilter.forEach((el, idx) => {
  const div = document.createElement('div');
  div.textContent = `${el.title}, ${idx}`;
  containerChanged.appendChild(div);
})
<div id="list">

</div>
<hr/>
<div id="list2">

</div>

Answer №3

If you need to remove items from the list, you can recreate it each time. This might be a costly process but is manageable if the cart doesn't contain too many items. Additionally, there's no requirement for jQuery as you can utilize DOMParser instead. Although I'm assuming the index of the item you wish to delete is the first one, you can adjust the index = null line accordingly. I trust this information proves helpful.

<!DOCTYPE html>
<html>
<head>
    <title></title>
</head>
<body>
    <button id="delete_item">Delete</button>
    <ul id="list-appunti"></ul>
<script type="text/javascript">
    
    function renderList(appuntiFilter) {

        const list_appunti = document.getElementById('list-appunti');
        list_appunti.innerHTML = '';
        
        for (i = 0; i < appuntiFilter.length; i++){
            
            var rand = Math.floor(Math.random()*1000)+1;

            const list_dom_string = `
                <div id="${rand}" class='row pb-3 mx-3 mt-3' style='border-bottom:1px solid #eeeeee;'>
                    <div id='fs-7' class='col-2 text-center font-weight-bold quant'>
                        ${appuntiFilter[i].count}x
                    </div>
                    <div class='col-3 pricep font-weight-bold text-right' style='color:#27c727;' id='price-app'>
                        ${parseFloat(appuntiFilter[i].price).toFixed(2).toLocaleString()}€
                    </div>
                    <div onclick='deleteItem("+i+")' class='col-2'><img src='delete.png' style='max-height:20px;' class='img-fluid' />
                    </div>
                </div>

            `;

            const parser = new DOMParser();
            const dom = parser.parseFromString(list_dom_string, 'text/html');

            list_appunti.appendChild(dom.body.children[0]);
            
        }

    }

    function deleteItem(list_appunti, index){

        list_appunti.splice(index ? index : 0, 1);

    }

    window.onload = function () {
        
        const appuntiFilter = [
           {title: "Apple", price: 0.50, count: 1},
           {title: "Pizza", price: 5.50, count: 1},
           {title: "Hamburger", price: 4.50, count: 1},
           {title: "Coca Cola", price: 0.99, count: 1},
        ];

        renderList(appuntiFilter);

        const delete_button = document.getElementById('delete_item');

        delete_button.addEventListener('click', function (e) {

            const index = null;

            deleteItem(appuntiFilter, index);
            renderList(appuntiFilter);

        }, true);
    }

</script>
</body>
</html>

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

Locate all entries with inclusive connections within a complex many-to-(many-to-many) relationship using sequelizejs

There is another related question in the Software Engineering SE. Let's think about entities like Company, Product, and Person. In this database, there exists a many-to-many relationship between Company and Product through a junction table called Co ...

Adjusting the Scaling Value to Match the Browser's Scaling Value

I'm struggling with a problem in HTML where the initial-scale function is not working as expected. When I zoom in on certain pages, it saves the zoom level. However, when I navigate to another page and then return to the original one, the zoom level r ...

Navigating Form Submission in Next.js

In this code snippet, I attempted to perform simple addition (ket=name + names). The desired outcome is a numerical sum displayed as “ket”. However, when entering 3 and 6 into the input fields, the result appears as 36 instead of 9. export default fu ...

Combining arrays of objects while maintaining data integrity in PHP

I am dealing with two arrays of objects: Array One: $array1 Array ( [0] => stdClass Object ( [id] => 100 [name] => John Doe ) [1] => stdClass Object ( [id] => 101 ...

Issues arose when attempting to navigate in a JavaScript handler within ASP.NET MVC

As a newcomer to Javascript, I hope my question isn't too basic. I have a button in my ASP.NET MVC 4 view: <input name="button" type="button" id="button1" value="Click me1"/> In order to create a click handler for the button, I've added ...

What is the best way to add a delay to ajax using setTimeout when working within a switch case

Is there a way to add a delay of 20 seconds to the Ajax function before displaying the next chat line? I'm trying to implement a feature where Ajax waits a few seconds before showing the next chat line that is submitted. For instance, imagine that t ...

Can you transform text with accents into plain ASCII characters?

I am seeking a solution in Javascript to convert accented letters and various encodings into plain English ASCII characters. The goal is to achieve the following transformations: éclair ~becomes~ eclair bär ~becomes~ bar привет ~becomes~ privet ...

Troubleshooting Problems with POST Requests in ExpressJS

Currently, I am working on developing a feature in NodeJS that allows users to upload files. However, I am encountering difficulties while attempting to make a simple POST request. In my index.ejs file, I have written code that generates a form and initia ...

Creating a calculator with JQuery and encountering challenges with performing multiple calculations

I've been working on a calculator using jQuery, but I'm encountering issues with the clear button not functioning properly after multiple calculations. On top of that, subsequent calculations are producing inaccurate results. I am seeking to enh ...

Filtering data in Angular based on specific dates

Upon receiving data from an Angular service, I have a JSON object structured like this: [ { "id": 2, "order_status": "R", "order_date": "2015-09-12T07:58:24.733834Z", "update_timestamp": "2015-10-05T04:22:44.904227Z" ...

Having issues delivering static JavaScript files to the client's browser using express.js

I'm looking to create a simple blog application using express.js, where I can write and store posts in a database directly from the browser. After some research, I found the ckeditor package, which allows for formatting before submission. I attempted ...

TimeStamp Recorder - Typescript

I'm trying to create a timer that counts the time when a button is pressed. Currently, I have managed to display the minutes and seconds on the screen as soon as the button is clicked. For example: 21(min):02(sec) What I am struggling with is updati ...

Caution in Three.JS: Potential WebGL Issue with Texture Mapping in Material Creation

I'm facing a challenge with a JSON file (map.js) that I use to load my geometry and material settings. This file is quite large, making manual edits challenging. Here is a snippet of what it looks like: "materials": [ { "DbgColor" : 2632490, "DbgInd ...

Experiencing problems with integrating Slim framework and AngularJS, such as encountering a 404 error

Although this may seem like a repeat question, I am encountering an issue with using AngularJS with Slim Framework web services. I have set up a webservice to retrieve a student record with a URL structure like: http://www.slim.local/api/getstudent/1 ...

The functionality of iOS 9 is hindering the accessibility of modal mobile links

On my website, I am using modal to display necessary information that requires users to click on buttons such as back and submit. However, the links seem broken even though they are supposed to redirect to another page. Whenever a button is clicked, the pa ...

Modify the NAME attribute when clicked using Jquery

I am attempting to modify the NAME attribute of a DIV with the text from a textbox using jQuery. Take a look at my code snippet: http://jsfiddle.net/e6kCH/ Can anyone help me troubleshoot this issue? ...

VueJS method for making an HTTP GET request

Attempting to make an http get request using Vue js. I can't seem to find any issues with the logic, although I'm not very experienced with vuejs. Continuously encountering these two errors: [Vue warn]: Error in mounted hook: "TypeError: Cann ...

Exploring the process of reading a character array with spaces from a file using C++

One of my current projects involves creating a maze map in a txt file. Below is the content of the .txt file: 7 7 e% %% %% %% %%% %%% %%% % % % % x % %% The numbers 7 and 7 represent the number of rows and columns, respectively. The spaces ...

Retrieve items from a JSON file based on the user input ID in a React project

Hi there, I'm looking for guidance on how to extract items by name from a JSON file based on user input. The JSON file contains both an id and name for each item. My goal is for the user to enter a number, which will then display the corresponding ite ...

Deploying a Vue/Nuxt application to Firebase as a Universal App with Server-Side Rendering (SS

I am currently facing challenges with deploying my Universal Nuxt.js app on Firebase. Despite attempting various methods, I have been unable to achieve full functionality. While SSR and hosting static assets seem to be functioning properly, middleware is ...