1

I'm learning react and making todo app and etc. but all the tutorial only shows using filter to remove items in array. I'll show you simple code.

const ProductItem = () => {
  const [users, setUser] = useState([
    { id: 1, name: "jenny" },
    { id: 2, name: "tom" },
    { id: 3, name: "juan" },
  ]);
  const removeUser = (user) => {
    //this is filter way
    // let newList = users.filter((x) => x.id !== user.id);
    // setUser([...newList]);
//this is delete item by index way
    users.splice(users.indexOf(user), 1);
    setUser([...users]);
  };
  return (
    <div>
      {users &&
        users.map((x) => (
          <div key={x.id}>
            <li>{x.name}</li>
            <button onClick={() => removeUser(x)}>remove</button>
          </div>
        ))}
    </div>
  );
};

export default ProductItem;

and both way is working correctly , but I just wonder if there's any reason that peoples using filter way?

jenny
  • 307
  • 6
  • 12
  • https://stackoverflow.com/questions/44435141/remove-object-in-array-using-filter-and-splice-which-one-is-best-approach-in-ang this might help you – Naresh Jul 12 '20 at 13:28
  • Splice mutates the array. Don't use it with react state, unless you copy the array first, since react depends on immutable state. – Nicholas Tower Jul 12 '20 at 13:31

2 Answers2

0

There is no hard and fast rule to use .filter all the time.

but all the tutorial only shows using filter to remove items in array.

Below are the main reasons:

.filter always returns a new array with the results and keep the original array intact.

React won't perform re-rendering if the reference has not changed or if it's mutated.

In your case, you can write setUser in one line a below if you use .filter

setUser(users.filter((x) => x.id !== user.id)); 

Where as .splice mutates the original users array and you should use spread operator while setting data with setUser else React won't perform re-rendering of component.

Remember one thumb rule less lines of code ~ less bugs.

Prathap Reddy
  • 1,688
  • 2
  • 6
  • 18
0

In Javascript, an array's length can be changed after it is initialized.

(I.E., a Javascript Array can be updated like a Linked List of C language)


splice() function can perform add and remove operations on an array.

splice() can be used when the requirement is to update the original data.

More information on splice():

https://www.w3schools.com/jsref/jsref_splice.asp


filter() function only selects a subset of elements that match a criteria, but does not delete anything from the original array.

filter() function need to be used when the original data must be kept intact.

More information on filter():

https://www.w3schools.com/jsref/jsref_filter.asp

Gopinath
  • 4,066
  • 1
  • 14
  • 16