Eliminating an element from an array depending on the value of its properties

I need to remove an object from my List array by matching its properties value with the event target ID. Currently, I am using findIndex method to locate the index ID that matches the event.target.id.

Below is an example of one of the objects in my list array:

{artist: "artist name",
genre: "RnB",
id: 1,
rating: 0,
title: "song name"}

This is the code snippet I'm working with:

  console.log(e.target.id);
  const list = this.state.playlist;
  list.splice(
    list.findIndex(function(i) {
      return i.id === e.target.id;
    }),
    1
  );

  console.log(list);
}

However, instead of removing the clicked item from the array, it always removes the last item.

When I try this approach:

const foundIndex = list.findIndex((i) => i.id === e.target.id)
console.log(foundIndex)

The console logs -1 as the output.

What could possibly be causing this issue?

Answer №1

To achieve this, you can utilize the filter method. Implement it to filter out objects from the state where the button's id does not match the current object's id being iterated over. By using filter, a new array is created which allows you to update your state without mutating the existing state (which should be avoided).

If you are working with React, here is a practical example:

const { Component } = React;

class Example extends Component {

  constructor() {
    super();
    this.state = {
      playlist: [
        {id: 1, artist: 'Billy Joel'},
        {id: 2, artist: 'Madonna'},
        {id: 3, artist: 'Miley Cyrus'},
        {id: 4, artist: 'Genesis'},
        {id: 5, artist: 'Jethro Tull'}
      ]
    };
  }

  // Extract the id from the button (coerce it to a number),
  // if it matches the object id,
  // exclude it from the new array
  // and proceed to update the state with the filtered array
  removeItem = (e) => {
    const { playlist } = this.state;
    const { id } = e.target.dataset;
    const updated = playlist.filter(obj => {
      return obj.id !== Number(id);
    });
    this.setState({ playlist: updated });
  }

  render() {
    const { playlist } = this.state;
    return (
      <div>
        {playlist.map(obj => {
          return (
            <div>{obj.artist}
              &nbsp;
              <button
                data-id={obj.id}
                onClick={this.removeItem}
              >Remove
              </button>
            </div>
          );
        })}
      </div>
    );
  }

};

ReactDOM.render(
  <Example />,
  document.getElementById('react')
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.2/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.2/umd/react-dom.production.min.js"></script>
<div id="react"></div>

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

What is the process for incorporating items from Slick Grid into a Multi Select TextBox?

Exploring the world of Slick Grid for the first time. Here is where I define my variables in JavaScript. var grid; var printPlugin; var dataView; var data = []; var selectdItems = []; var columns = [ { id: "Id", name: "Id", field: "Id", sortable: t ...

Troubleshooting Firefox in Python Selenium: When using driver.execute_script to delete text characters using JQuery, encountering "SecurityError: The operation is insecure" error

Currently working with Selenium 3.141.0 using Python and Firefox 88.0 with geckodriver 0.29.1. In the past, I successfully used the following JavaScript code to remove unwanted characters (like ®) from web pages, as referenced in this answer: driver.exec ...

Tips for preventing the collapse of a table row using a button?

I have implemented a Bootstrap collapse feature on my table row. Currently, the collapse can be triggered by clicking anywhere on the row, which is working as intended. However, I would like to make one exception - if the user clicks on the desktop icon i ...

The autocomplete feature fails to properly highlight the selected value from the dropdown menu and ends up selecting duplicate values

After working on creating a multiple select search dropdown using MUI, my API data was successfully transformed into the desired format named transformedSubLocationData. https://i.stack.imgur.com/ZrbQq.png 0: {label: 'Dialed Number 1', value: &a ...

Unable to render the JSON data that was retrieved from a jQuery AJAX request

I am having trouble displaying JSON data that is returned from an AJAX call. Can someone please assist me? I am new to this. $.ajaxSetup({ cache: false, timeout: 5000 }); //String.prototype.toJSON; var the_object = {}; function concatObject(obj) { ...

What is the process for generating SDF-Icons (Mapbox's specialized icons) from PNG files?

I am currently working on changing the icon color of an icon image in Mapbox. According to Mapbox documentation, the only way to do this is by using sdf-icons (https://docs.mapbox.com/mapbox-gl-js/style-spec/layers/#paint-symbol-icon-color). After hours o ...

What could be causing the issue of why the null check in JavaScript isn't functioning properly

function getProperty(property) { console.log(localStorage[property]) //Displays “null” if(localStorage[property] == null) { console.log('Null check') return false; } return localStorage[property]; } The log outputs "nu ...

Instructions on how to determine if a client is a "desktop terminal"

So here's the deal: I have a suspicion about thin clients accessing my website. Is there a way to test if a client is a thin client without causing it to lag with JavaScript animations? I want to provide a simplified version of the site for these clie ...

Is there a way for me to properly initiate the Material UI Modal from the parent component?

This is the main component: import React from 'react'; import ChildModal from 'ChildModal'; const MainComponent = () => ( <div> <span>Click </span> <a>HERE TO OPEN MODAL</a> <div> ); ...

"Troubleshooting a glitch encountered while making an invokeAPI call with Azure Mobile

Working on integrating my Angular App with Azure Services as the back end. Initially, I used the standard $http call: $http({ method: 'POST', url: "https://services.example.com/Api/myApi", headers : { "Content-Type" ...

What do you believe to be superior: Vue UI design?

Scenario: Application managing multiple user roles. A view with extensive conditional rendering in the template. a) Is it preferable to have numerous conditional statements in a single view's template? b) Should separate views be created for each ro ...

Enhance the appearance of your custom Component in React Native by applying styles to Styled Components

I have a JavaScript file named button.js: import React from "react"; import styled from "styled-components"; const StyledButton = styled.TouchableOpacity` border: 1px solid #fff; border-radius: 10px; padding-horizontal: 10px; padding-vertical: 5p ...

Refresh the information displayed in the open Google Maps Infowindow

Experimenting with extracting JSON data from a bus tracker website and integrating it into my own version using Google Maps. Although not as visually appealing, I'm struggling to update an infowindow while it remains open. Despite finding some example ...

Strings that automatically adjust to fit the content from a JSON object

I have a JSON object with a long string that I want to display. The string looks like this: "String":"<p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever si ...

Guide on implementing jQuery Validation plugin with server-side validation at the form level

Does anyone have a suggestion for how to handle server-side validation errors that occur after passing the initial client-side validation on a form? $("#contact_form").validate({ submitHandler: function(form) { $.ajax({ type: 'POST', ...

Struggling with the conundrum of aligning a constantly changing element amid the

I was optimistic about the code I wrote, hoping it would work out in the end. However, it seems that my expectations might not be met. Allow me to provide some context before I pose my question. The animation I have created involves an SVG element resembl ...

What is the best way to display a progress bar as a percentage?

Is there a way to visually represent the progress of an upload on the screen using percentages? I want to display a bar that starts at 0% and updates with the percentage from the percentComplete variable. Once the upload is finished, I'd like to show ...

Perform an asynchronous reload of DataTables using ajax.reload() before calling a function

I need help extracting real-time data from a datatable and populating a form for editing when an edit button is clicked on each row. Despite my efforts, the ajax.reload() function doesn't load the table in time to fill the form with correct data. The ...

What language should be used for JSON data formats?

I am dealing with a JSON file named myjson.cfg that has the following structure: { "values": { "a": 1, "b": 2, "c": 3, "d": 4 }, "sales": [ { "a": 0, "b": 0, "c": 0, "d": 0, ...

Guide on displaying link parameter information on a separate webpage using only JavaScript

While doing some research, I came across an issue. I have a page called specifications.html with three links: details.html?id=1, details.html?id=2, and details.html?id=3. My goal is to display the details of each link when someone clicks on it. For examp ...