title: Deleting item from state array in react
body: <p>I have a delete function that looks like this:</p>
  
  <pre><code>   this.deleteItem = item =&gt; event =&gt; {
        const { res, selectedItems } = this.state;
        res.splice(res.indexOf(item), 1);
        selectedItems.splice(res.indexOf(item), 1);
  
        this.setState({
          res
        });
      };
  </code></pre>
  
  <p>Here, the <code>res</code> is the list of items displayed on the page, and <code>selectedItems</code> is a list of which of those items are selected. When an item from <code>res</code> is deleted, <code>selectedItems</code> should be updated to remove the index of that item from the list.</p>
  
  <p>Whenever I try to delete a specific item however, it just deletes the last item added to the array, rather than the item that corresponds to the index of the target clicked. Something must be going on with the way it's being indexed, but I've been having trouble identifying the source.</p>
  
  <p>I've also tried as referenced <a href="https://stackoverflow.com/questions/36326612/delete-item-from-state-array-in-react">here</a>, but this didn't work since I need to take in <code>item</code> as a parameter.</p>
  
  <p>What would be a good way to go about this?</p>
  
  <p>Thank you very much.</p>
  
  <p>EDIT: Changed the function to look like @HMK's response. After an item is deleted, the output of <code>console.log(res)</code> in the render method is an array of objects which has the form:</p>
  
  <pre><code>res 
  (9) […]
  ​
  0: Object { id: 0, name: "a", description: "description of a", … }
  ​
  1: Object { id: 2, name: "b", description: "description of b", … }
  ​
  2: Object { id: 3, name: "c", description: "description of c", … }
  ​
  3: Object { id: 4, name: "d", description: "description of d", … }
  ​
  4: Object { id: 5, name: "e", description: "description of e", … }
  ​
  5: Object { id: 6, name: "f", description: "description of f", … }
  ​
  6: Object { id: 7, name: "g", description: "description of g", … }
  ​
  7: Object { id: 8, name: "h", description: "description of h", … }
  ​
  8: Object { id: 9, name: "i", description: "description of i", … }
  ​
  length: 9
  ​
  &lt;prototype&gt;: Array []
  </code></pre>
  
  <p>The output of <code>console.log(JSON.stringify(item,undefined,2));</code> in the <code>deleteItem</code> function is the object that is deleted from the array.</p>
  
  <p>e.g.:</p>
  
  <pre><code>{
    "id": 10,
    "name": "j",
    "description": "description of j",
    "icon": "jIcon",
    "selected": false
  }
  
  </code></pre>
  
  <p>When all items on the page are selected, the output of <code>console.log("selecteditems:", JSON.stringify(selectedItems))</code>:</p>
  
  <pre><code>selecteditems: [0,1,2,3,4,5,6,7,8,9,10]
  </code></pre>