89

I have an array of objects. I need to add a function to remove an object from my array without using the "this" keyword.

I tried using updateList(list.slice(list.indexOf(e.target.name, 1))). This removes everything but the last item in the array and I'm not certain why.

const defaultList = [
{ name: "ItemOne" },
{ name: "ItemTwo" },
{ name: "ItemThree" }]

const [list, updateList] = useState(defaultList);

const handleRemoveItem = e => {
    updateList(list.slice(list.indexOf(e.target.name, 1)))
}

return (
    {list.map(item => {
        return ( 
            <>
            <span onClick={handleRemoveItem}>x </span>
            <span>{item.name}</span>
            </>
        )}
    }
)

Expected behaviour: The clicked item will be removed from the list.
Actual behaviour: The entire list gets removed, minus the last item in the array.

4
  • For starters there is no name on a span. Do some basic debugging and see what e.target.name even is. Then...read the documentation for how slice() works as well as how indexOf() works. You have multiple problems in that method
    – charlietfl
    Commented Aug 3, 2019 at 19:41
  • You're right there's no name on a span. That's why the name refers to the item mapped from the array. Did you even read the post? Commented Aug 3, 2019 at 19:53
  • No it does not in the context you are using onClick={handleRemoveItem}. Did you inspect it inside the function?
    – charlietfl
    Commented Aug 3, 2019 at 19:56
  • @collinswade408 see my solution below. That should give you some insight on how to complete your solution and why your code does not work. Commented Aug 3, 2019 at 20:35

8 Answers 8

111

First of all, the span element with the click event needs to have a name property otherwise, there will be no name to find within the e.target. With that said, e.target.name is reserved for form elements (input, select, etc). So to actually tap into the name property you'll have to use e.target.getAttribute("name")

Additionally, because you have an array of objects, it would not be effective to use list.indexOf(e.target.name) since that is looking for a string when you are iterating over objects. That's like saying find "dog" within [{}, {}, {}]

Lastly, array.slice() returns a new array starting with the item at the index you passed to it. So if you clicked the last-item, you would only be getting back the last item.

Try something like this instead using .filter(): codesandbox

import React, { useState } from "react";
import ReactDOM from "react-dom";

import "./styles.css";

const App = () => {
  const defaultList = [
    { name: "ItemOne" },
    { name: "ItemTwo" },
    { name: "ItemThree" }
  ];

  const [list, updateList] = useState(defaultList);

  const handleRemoveItem = (e) => {
    const name = e.target.getAttribute("name")
    updateList(l => l.filter(item => item.name !== name));
  };

  return (
    <div>
      {list.map(item => {
        return (
          <>
            <span name={item.name} onClick={handleRemoveItem}>
              x
            </span>
            <span>{item.name}</span>
          </>
        );
      })}
    </div>
  );
};

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
4
  • A <span> can't have a name attribute or properly. Commented Aug 3, 2019 at 21:15
  • @WillJenkins Sure it can, you just wouldn't be able to see it via event.target.name. Commented Aug 3, 2019 at 21:16
  • Check the spec, a <span> can't have a name w3.org/TR/REC-html40/index/attributes.html Commented Aug 3, 2019 at 21:23
  • 1
    What if two elements have the same name value? It will remove both elements, @ChrisNgo
    – Pep
    Commented Jan 25, 2022 at 14:30
38

You can use Array.filter to do this in a one-liner:

const handleRemoveItem = name => {
    updateList(list.filter(item => item.name !== name))
}

Eta: you'll also need to pass the name of your item in your onClick handler:

{list.map(item => {
    return ( 
        <>
        <span onClick={() =>handleRemoveItem(item.name)}>x </span>
        <span>{item.name}</span>
        </>
    )}
26
const defaultList = [
    { name: "ItemOne" },
    { name: "ItemTwo" },
    { name: "ItemThree" }
]

const [list, updateList] = useState(defaultList);

const handleRemoveItem = idx => {
    // assigning the list to temp variable
    const temp = [...list];

    // removing the element using splice
    temp.splice(idx, 1);

    // updating the list
    updateList(temp);
}

return (
    {list.map((item, idx) => (
      <div key={idx}>
        <button onClick={() => handleRemoveItem(idx)}>x </button>
        <span>{item.name}</span>
      </div>
    ))}

)
3
  • 1
    Doesn't the temp variable get left in memory after its done with this example? That wouldn't be good for large work loads.
    – Ian Smith
    Commented May 31, 2020 at 23:01
  • 2
    @IanSmith any suggestions for that?
    – Kevin
    Commented Sep 15, 2021 at 0:34
  • 1
    JavaScript collects its garbage as values go out of scope. See stackoverflow.com/q/31686412/1264804
    – isherwood
    Commented Jul 28, 2022 at 20:38
2

Small improvement in my opinion to the best answer so far

import React, { useState } from "react";
import ReactDOM from "react-dom";

import "./styles.css";

const App = () => {
  const defaultList = [
    { name: "ItemOne" },
    { name: "ItemTwo" },
    { name: "ItemThree" }
  ];

  const [list, updateList] = useState(defaultList);

  const handleRemoveItem = (item) => {
    updateList(list.filter(item => item.name !== name));
  };

  return (
    <div>
      {list.map(item => {
        return (
          <>
            <span onClick={()=>{handleRemoveItem(item)}}>
              x
            </span>
            <span>{item.name}</span>
          </>
        );
      })}
    </div>
  );
};

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

Instead of giving a name attribute we just send it to the handle function

1
  • 2
    got 2 small mistakes there I think. fix them to: 1) const handleRemoveItem = (name) => { ... // etc 2) onClick={()=>{handleRemoveItem(item.name)}}
    – okram
    Commented Jul 25, 2021 at 8:59
2

Redundant one liner - would not recommend as hard to test / type / expand / repeat / reason with

 <button onClick={() => setList(list.slice(item.id - 1))}

A version without exports:

 const handleDeleteItem = id => {
     const remainingItems = list.slice(id - 1)
     setList(remainingItems);
}

However I would consider expanding the structure of your logic differently by using helper functions in another file.

With that in mind, I made one example for filter and another for slice. I personally like the slice option in this particular use-case as it makes it easy to reason with. Apparently, it is also slightly more performant on larger lists if scaling (see references).

If using slice, always use slice not splice unless you have good reason not to do so as it adheres to a functional style (pure functions with no side effects)

// use slice instead of splice (slice creates a shallow copy, i.e., 'mutates' )
export const excludeItemFromArray = (idx, array) => array.slice(idx-1)

// alternatively, you could use filter (also a shallow copy)
export const filterItemFromArray = (idx, array) => array.filter(item => item.idx !== idx)

Example (with both options filter and slice options as imports)

import {excludeItemFromArray, filterItemFromArray} from 'utils/arrayHelpers.js'

const exampleList = [
    { id: 1, name: "ItemOne" },
    { id: 2, name: "ItemTwo" },
    { id: 3, name: "ItemThree" }
]

const [list, setList] = useState(exampleList);

const handleDeleteItem = id => {
  
    //excluding the item (returning mutated list with excluded item)
    const remainingItems = excludeItemFromArray(id, list)

    //alternatively, filter item (returning mutated list with filtered out item)
    const remainingItems = filterItemFromArray(id, list)

    // updating the list state
    setList(remainingItems);
}

return (
    {list.map((item) => (
      <div key={item.id}>
        <button onClick={() => handleDeleteItem(item.id)}>x</button>
        <span>{item.name}</span>
      </div>
    ))}
)

References:

1
  • These links have proved an interesting read!
    – Harrison
    Commented Nov 25, 2022 at 11:43
1

I think this code will do

let targetIndex = list.findIndex((each) => {each.name == e.target.name});
list.splice(targetIndex-1, 1);

We need to check name value inside object so use findIndex instead. then cut the object start from target index to 1 array after target index.

Codepen

From your comment your problem came from another part.

Change this view section

    return ( 
        <>
        <span onClick={() => handleRemoveItem(item) }>x </span>
        <span>{item.name}</span>
        </>
    )}

change function handleRemoveItem format

const handleRemoveItem = item => {
    list.splice(list.indexOf(item)-1, 1)
    updateList(list);
}
7
  • 2
    Best not to mutate original array
    – charlietfl
    Commented Aug 3, 2019 at 19:42
  • Thanks for the quick answer, but this returns a typescript error Argument of type '(each: { name: string; }) => void' is not assignable to parameter of type '(value: {name: string; }, index: number, obj: { name: string;}[]) => boolean'. Commented Aug 3, 2019 at 19:44
  • You can check the code pen. I think the issue in another part not this part; Commented Aug 3, 2019 at 19:49
  • I don't know why you use const because it's not editable. Commented Aug 3, 2019 at 19:51
  • 1
    Done. You can check it again.. Hope your problem gone! Commented Aug 3, 2019 at 20:10
0

Using this pattern, the array does not jump, but we take the previous data and create new data and return it.

 const [list, updateList] = useState([
    { name: "ItemOne" },
    { name: "ItemTwo" },
    { name: "ItemThree" }
  ]);

     updateList((prev) => {
                return [
                    ...prev.filter((item, i) => item.name !== 'ItemTwo')
                ]
            })
1
  • To reduce the number of lines, you could remove the return statement like so: updateList((prev) => ([...prev.filter((item) => item.name !== 'ItemTwo')]))
    – Harrison
    Commented Nov 24, 2022 at 9:23
-1

This is because both slice and splice return an array containing the removed elements.

You need to apply a splice to the array, and then update the state using the method provided by the hook

const handleRemoveItem = e => {
    const newArr = [...list];
    newArr.splice(newArr.findIndex(item => item.name === e.target.name), 1)
    updateList(newArr)
}
4
  • Thanks for the quick response. The above did not work unfortunately, so i tried const newArr= list.splice(list.indexOf(e.target.name, 1)) updateList(newArr) which gives me the same issue as my original post. :( Commented Aug 3, 2019 at 19:50
  • That's because the splice method is still returning an array of removed elements, even if you store it in a variable.
    – Morphyish
    Commented Aug 3, 2019 at 19:52
  • You can't use indexOf() on array of objects this way
    – charlietfl
    Commented Aug 3, 2019 at 19:54
  • Yeah, I just made a edit, I copy/pasted this part of the code from the question and didn't pay attention to the data structure.
    – Morphyish
    Commented Aug 3, 2019 at 19:56

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.