Skip to content
Advertisement

Delete an element from the array and update order

I have an array of objects in the state. The object has the order property. I need order prop for drag and drop. The list is sorted by order. Also, there is a function to remove an item from the list. How to correctly remove an element from an array with updating the order property?

  const deleteTodo = (id) => {

    //I tried using map but it doesn't work

    setTodos(todos.map((todo, index) => {
      if (todo.id !== id) {
        return { ...todo, order: index + 1 } 
      }
      return todo
    }))

  }

/* for example:
[{title: 'apple', order: 1}, {title: 'banana', order: 2}, {title: 'pear', order: 3}] => delete banana => [{title: 'apple', order: 1}, {title: 'pear', order: 2}] */

I wrote this solution based on the suggested options:

  const deleteTodo = (id) => {
    const newTodos = todos
      .filter(todo => todo.id !== id)
      .map((todo, index) => ({ ...todo, order: index + 1 }))
    setTodos(newTodos)
  }

Advertisement

Answer

  1. Filter to delete
  2. map to change the order value

const items = [{
  title: 'apple',
  order: 1
}, {
  title: 'banana',
  order: 2
}, {
  title: 'pear',
  order: 3
}]
//Delete {title: 'banana', order: 2}
const newItems = items.filter(el => el.title !== "banana").map(el => el.order > 2 ? ({ ...el,
  order: el.order - 1
}) : el)

console.log(newItems)
Advertisement