cannot successfully remove items from array

I'm working with an array called cartarray that has the following format.

1: {id: "1510-01-312-3501-OkqcPp3xJwfgmNinwGsKZmAa8xt1-1514542566148", name: "AIRPLANE UTILITY", price: "$90", quantity: "1"}

2: {id: "1510-00-033-6312-OkqcPp3xJwfgmNinwGsKZmAa8xt1-1514540733034", name: "AIRPLANE UTILITY", price: "$43", quantity: "3"}

3: {id: "1510-00-033-6312-OkqcPp3xJwfgmNinwGsKZmAa8xt1-1514540733034", name: "AIRPLANE UTILITY", price: "$43", quantity: "1"}

The HTML structure below is dynamically created based on the information in the array above.

cartarry.products.forEach(function(element) {
    var id = element.id;
    var itemname = element.name;
    var itemprice = element.price;
    var itemcard = `
            <div class="product" id="${id}">
                  <div class="product-image">
                    <img src="https://s.cdpn.io/3/dingo-dog-bones.jpg">
                  </div>
                  <div class="product-details">
                    <div class="product-title">Dingo Dog Bones</div>
                    <p class="product-description"> ${itemname}</p>
                  </div>
                  <div class="product-price">${itemprice}</div>
                  <div class="product-quantity">
                    <input type="number" value="2" min="1">
                  </div>
                  <div class="product-removal">
                    <button class="remove-product">
                      Remove
                    </button>
                  </div>
          <div class="product-line-price">25.98</div>
          </div>

      `;
  itemcontainer.innerHTML += itemcard;
})       

My goal is to remove the clicked item from the array, so I attempted the following script:

var items = cartarry.products;
$('.product').on('click', function(element) {

  console.log(this.id)

  var index = items.indexOf(this);
  console.log(index)

  var i = items.indexOf(this);
  if (i != -1) {
      items.splice(i, 1);
  }
})  

However, regardless of which item I click, the 'index' value keeps returning as -1 preventing item deletion. How can I resolve this issue and successfully delete the clicked item from the array?

Answer №1

To start off, you have instantiated an "item" object from the "cartarry.products" array. It is important to note that deleting the element from the "item" object does not remove it from the original "cartarry.products" array. To find and delete an element by a specific property, you can utilize the following code snippet:

  var index = cartarry.products.map(function(element) {
          return element.id;
        }).indexOf(this.id);

I have prepared a Plunker demonstration for your reference:

https://embed.plnkr.co/qWlUy6NxAG3ERjDXD0LL/

Answer №2

The element this cannot be found in the array, as it is a part of the DOM.

To locate the index of the item containing your id, you can utilize Array.findIndex

var findId = this.id;

var match = items.findIndex(function (el) {
  return el.id == findId;
});

if (match > -1) {
  items.splice(match, 1);
}

Answer №3

$('.item').on(
    'click',
    ({ id }) => shoppingCart.items = shoppingCart.items.filter(item => item.id != id)
)

In the initial code you provided, this represented the clicked DOM element instead of the actual product. The revised code captures the id from the clicked element and filters out only the items in the shopping cart that do not match the clicked id.

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

Ways to implement a package designed for non-framework usage in Vue

Alert This may not be the appropriate place to pose such inquiries, but I am in need of some guidance. It's more about seeking direction rather than a definitive answer as this question seems quite open-ended. Overview I've created a package th ...

The function is failing to trigger when clicked within an Angular 5 app

Hey everyone, I'm facing a minor issue with my Angular 5 project. I am trying to use a common session check method from a shared TypeScript file. This method is used both when the page loads and when the logout button is clicked to redirect the user t ...

Tips for Preventing Repetition of Locations on a Website for Reviewing Places

I am currently working on creating a directory specifically for hospitals, similar to the "Yellow Pages." Can anyone advise on how to avoid duplication of pages for the same hospital? I was considering using longitude and latitude registration, but it se ...

Customizing Date Format for Multiple Datepickers on a Single Page using Angular Material (md-datepicker)

I am currently working with angular material and using md-datepicker. My goal is to be able to set different date formats depending on the user's selection. For example, if the user chooses 'daily', I want the datepicker to display 'MM/ ...

Simple guide on converting a JavaScript object into JSON

I am currently facing a challenge in converting the following JavaScript object into valid JSON format: [{ '"Sno"': '"1"', '"Purchase Date Time"': '"2017-11-14 14:09:32"', '"Txn Type"': '"COD"&apo ...

Attempting to download an image through an axios fetch call

There is an issue I am facing while trying to retrieve an image from the website www.thispersondoesnotexit.com. function getImage() { axios({ method: 'get', url: 'https://www.thispersondoesnotexist.com/image' }) ...

In what ways can you toggle the visibility of table rows and data dynamically with the onchange event in HTML?

I'm dealing with an HTML code that can dynamically change table data based on user selection. Here's the snippet of my HTML code: Select an option: <select name='set' id="set" class="selectpicker" onchange='displayFields(this. ...

`On mouseup event, changing specific text`

I've been working on a real-time HTML highlighter that surrounds selected text with span elements containing a background property. Check out the fiddle here: https://jsfiddle.net/4hd2vrex/ The issue arises when users make multiple selections, leadi ...

Laravel and Vue: Footer-div component not recognized

After reading an article on Vue.js from this source, I decided to start learning it. Everything was going smoothly with my SPA until I tried to add a new component and encountered this error: Unknown custom element: - have you registered the component c ...

Error loading Azure Active Directory web form: Server returned a 401 status code for the requested resource

I recently made changes to my web site (incorporating a web form and entity framework) to use AAD connection, following the guidance in this insightful blog post. However, I am encountering an issue where scripts and css files are not loading properly. Th ...

Assistance with Javascript to optimize page performance

As a newcomer to Javascript, I acknowledge that my question might be basic. I have a JS script in the head of my application that is causing a delay in page loading time on examplepage.php. The script is as follows: <script type="text/javascript"> $ ...

Tips for utilizing .html?q= as a hyperlink shortening method

I've been thinking, is there a way to create a simple JavaScript shortening tool where I can manually input the code for JavaScript? Like this: function shortenUrl() { window.location.href = "http://link.com"; } In this code snippet, 12345 repre ...

Unable to retrieve Object property using computed method in Vue 3 vuex results in undefined value

When attempting to display the values of a computed property in the template using the syntax {{todo[0]['title']}}, I am receiving an 'undefined' output. However, using {{todo[0]]}} allows me to render the entire object. My goal is to b ...

What are the techniques used to minimize JavaScript functions?

Is there a more efficient way to reduce the amount of JavaScript code needed for functions that share the same call procedure? I'm struggling to find a clear explanation but here's the code snippet below... JavaScript: $(function() { $( &a ...

An error in node.js has been triggered due to the spawn ENO

I recently created a node.js app using the express-generator tool, but I'm encountering an unusual problem. Whenever I try to access a certain page in the browser for the second time, it doesn't load properly. Instead, the node process ends with ...

A recursive function in ECMAScript 6 using promises

I am currently in the process of developing a foundational class for sequelize.js. This particular class will handle the association of all related tables, with the includeFk function responsible for executing this task. The function involves the use of pr ...

Discover in Mongo DB with Mongoose, except for the find() method, which excludes documents containing a specific property

I'm searching for a condition in Mongoose that will help me locate all users except those with the role 'Admin':2000. Keep in mind that admin users also have other roles, such as "User" and "Editor", as shown below: { "name": &q ...

Exploring MySQL data parsed from JSON with customized user input

Greetings! Currently, I am in the process of developing an HTML5 App that retrieves and displays data from a remote MySQL database. At this moment, the code below successfully fetches data and showcases it within the application: Moreover, my app contain ...

unable to display images from a folder using v-for in Vue.js

Just getting started with Vuejs and I have two pictures stored on my website. The v-for loop is correctly populating the information inside databaseListItem. The path is /opt/lampp/htdocs/products_db/stored_images/cms.png https://i.stack.imgur.com/969U7.p ...

Invoking WinJS.Binding.List.createFiltered with an asynchronous call to the predicate function

Is there a way to wait for the async operation in this code snippet and use its result as the predicate instead of always returning false? return someList.createFiltered(function(item) { var filter = false; var ...