0

I'm trying to learn to react online and I understood everything except this line code

const removeItem = (id) => {
    let newPeople = people.filter((person) => person.id !== id);

    setPeople(newPeople);

  };

especially how person.id !== idremoves the item from list and add to new list

here is the full code

import React from 'react';
import { data } from '../../../data';
const UseStateArray = () => {
  const [people, setPeople] = React.useState(data);

  const removeItem = (id) => {
    let newPeople = people.filter((person) => person.id !== id);

    setPeople(newPeople);

  };
  return (
    <>
      {people.map((person) => {
        const { id, name } = person;
        return (
          <div key={id} className='item'>
            <h4>{name}</h4>
            <button onClick={() => removeItem(id)}>remove</button>
          </div>
        );
      })}
      <button className='btn' onClick={() => setPeople([])}>
        clear items
      </button>
    </>
  );
};

export default UseStateArray;
dilbro
  • 35
  • 7
  • 1
    `person.id !== id` isn't removing the item. `filter` function accepts a [predicate](https://stackoverflow.com/questions/1344015/what-is-a-predicate) and only selects the items which when passed to the predicate, return `true`. In this case, `newPeople` is a list of people who's id is not the same as the `id` passed to the `removeItem` function. – vighnesh153 Nov 16 '22 at 16:08
  • These are just higher order array methods, I can't explain all of it in this comment, see: https://youtu.be/rRgD1yVwIvE?t=330 – TechTycho Nov 16 '22 at 16:10

2 Answers2

2

first you shold khow how filter works,

The filter() method creates a new array filled with elements that pass a test provided by a function.

in your case test is person.id !== id, if test passed for an element that element will be in new array. otherwise element will not be in new array. is it clear?

Kamran Davar
  • 427
  • 2
  • 12
0

The filter method creates a shallow copy of an array but not the whole array but only those elements that fulfills the predicate.

So newPeople will contain a copy of all the elements within people that it's people[element].id is different than id.

Visit https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter for additional details of filter method.