Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

176
Views
filtering out an array of items setting state

I am looking to filter through an array and return all elements of the array except the element which has been clicked on, so I have a map of list elements each with a key={index} of their map, onClick it should call my remove function, and pass in the index of the element to be removed, I then need to filter over that array, remove the element, update state, and send this information to my backend.

here is the delete function

  const deleteItem = (id) => {
    // use filter, to loop through all pieces of index
    const element = list.todoItems.indexOf(id - 1);
    setList({ todoItems: list.todoItems.filter(element !== id) });
    console.log(list.todoItems);
    dispatch(updateTodo(list));
  };

here is the mapped array

{list.todoItems.map((Item, index) => (
                <div
                  // setup anonymous function, that will call
                  // ONLY when the div
                  // is clicked on.
                  key={index}
                  onClick={() => deleteItem(index)}
                >
                  {/* list item, gets text from props */}
                  <li>{Item}</li>
                </div>
              ))}

I must be missing something, because this should work, Though i may have to shift gears and have each item as an actual object in my database, though id rather not do this as i feel an array of strings is more than appropriate for this app.

about 4 years ago · Santiago Trujillo
2 answers
Answer question

0

Remove your indexOf logic and this will work.

You don't have to find the index of the array because you're already receiving it as a parameter.

const deleteItem = (id) => {
        setList({ todoItems: list.todoItems.filter((_, filterID) => filterID !== id) });
        console.log(list.todoItems);
        dispatch(updateTodo(list));
 };
about 4 years ago · Santiago Trujillo Report

0

You don't need to subtract one from the index on the indexOf function

And for this case, splice works better than filter

const deleteItem = (id) => {
  const element = list.todoItems.indexOf(id);
  setList({ todoItems: {...list}.todoItems.splice(element, 1)});
  dispatch(updateTodo(list));
};
about 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!