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

Discovering methods to access properties from another function

Can I access the value of variable w from another function? <script type="text/javascript"> var first = { myFirst: function(){ var w= 90; var q=12; }} var second= { mySecond: function(){ first.myFirst.w }} </script> ...

Is it possible that .focus() does not function on a duplicated object?

Greetings to all! I have created a form with rows of input text fields. Users can add as many rows as needed by clicking the 'add row' button. The functionality to clone() for adding rows is working perfectly. In each row, an input field can o ...

How to execute a JavaScript function within PHP code

Hey there, seeking some assistance. On my main page index.php, I have a simple js function named function1() that opens test.php as a pop-up window when clicked. The content in this pop-up window comes from another page called p1.php. Now, I need to set it ...

Designing an image transformation page by segmenting the image into fragments

Does anyone have insight into the creation process of websites like this one? Are there any plugins or tools that can assist in building something similar? ...

Is jQuery(document) loaded on 'focus'?

Whenever a user clicks on an input, I intend to activate a method. The code I currently have is: jQuery(document).on('focus click', function(e){ console.log("focused on " + $(e.target).attr('id')); }); However, when I focus on ...

Unusual Actions: Removing a specific item from an array using ReactJS

In my current approach, I am utilizing a technique to remove an object from an array stored in the state: export default function App() { const [gridData, setGridData] = useState({field1:"Placeholder",data:[]}); const data = [ { numstart: 1,numend ...

React: When state is updated and a console.log is used, the console displays the previous state instead of the updated

Upon clicking the button, a peculiar sequence unfolds - the console displays 0 and the page refreshes to show 1 function App() { const [count, setCount] = useState(0); const addOne = () => { setCount(count + 1) console.log(count) } ...

Is my data secure in Node.js RAM?

I have developed a web application that enables users to create personal pages using Express and Node.JS. Each page is represented as an object, allowing for the creation of new ones with the syntax: new privatePage(name, pswd). As a result, all passwords ...

Breaking down a statement into individual elements within an array, incorporating keys alongside the elements within the array

let condition = "[AccNum]==true&&[AccNum]==[ARID]&&[AccNum]==aaaa || [ARID]!=true&&[DOB]&gt;[ARID] || [DOB]&gt;bbb&&[DOS]&gt;=[ARID]&&[DOS]&lt;[Gender]&&[66642]&lt;=cccc&&[66642] I ...

What are the steps to integrate jQuery into an Angular 8 application?

I am currently working on an application that relies on SignalR for communication with a desktop application. In order to make use of SignalR, I include jQuery in my .ts file. However, after migrating from Angular 7 to Angular 8, it appears that this setup ...

What is the best way to apply a jQuery function to multiple div elements simultaneously?

I am looking to implement a show/hide feature for a <div> using JavaScript and DOM properties. The idea is to use JavaScript's onclick() function with two buttons, show and hide, each in their respective <div>. Here is how it would ideall ...

Utilize dropdown1 to dynamically populate dropdown 2 in AngularJS

Here is the HTML code snippet I am currently working with: <select ng-controller="category" ng-model="selectedTestAccount" ng-options="c.category for c in categories track by c.categoryID" ></select> <select ng-controller="subcategory" ng ...

Tips for Providing Real-Time Data for a Dynamic Chart in d3

I have a line chart sample from D3, and the issue I'm facing is that I need to continuously feed live data from a server at certain time intervals and use D3 to draw the chart based on this dynamic data. Despite my efforts to search for a solution, I ...

A guide on performing CRUD operations on locally stored JSON data using React JS

Retrieve the JSON data from any endpoint and store it locally fetch("any endpoint") .then((response) => response.json()) .then((responseJson) => { this.state ={ data:responseJson } }) How to perform CRUD operations on a sample JSO ...

Navigating through an array of objects with Node.js

Recently, I integrated the ChartJS library into my Node web app to visualize data. The following is nested in a script tag on an EJS template page: <script> let playerStatChart = new Chart(myChart, { type: 'bar', data: { la ...

The ability to submit a conversation chat is currently

I encountered an issue when attempting to submit a chat, and I received the error message 'handlebar is not define'. I followed the code tutorial provided in this link: https://codepen.io/drehimself/pen/KdXwxR This is the screenshot of the error ...

Typography splits into a second line within the grid on the toolbar

I need help with my Appbar design. I want to align the title (Lorem ipsum text) on the left and the buttons on the right. However, when I tried implementing the code below, I noticed that there seems to be a maximum width causing the text to break into t ...

Where is the first next() call's argument located?

I'm facing an issue with a simple generator function function *generate(arg) { console.log(arg) for(let i = 0; i < 3;i++) { console.log(yield i); } } After initializing the generator, I attempted to print values in the console: var gen ...

Disregarding 'zIndex' directive within JavaScript function, an image stands apart

There is an issue with the z-index values of rows of images on my webpage. Normally, the z-index values increase as you scroll further down the page. However, I want certain items to have a lower z-index than the rest (except on hover). These items are i ...

Having trouble with test coverage in Mocha using Blanket?

I have a Node application that I want to test and generate a coverage report for. I followed the steps outlined in the Getting Started Guide, but unfortunately, it doesn't seem to be working correctly. In my source code file named src/two.js: var tw ...