What is the advantage of using $ splice (from immutability-helper) over a filter to remove an element from an array in React?

I use immutability-helper to do CRUD operations with status data and want to know if I should always use $spliceto delete data or use it normally filter(since it is not destructive)?

For example, let's say I have an array of objects:

todos = [
 {id: 1, body: "eat"},
 {id: 2, body: "drink"},
 {id: 3, body: "sleep"},
 {id: 4, body: "run"}
]

Given the id of an element, I can remove it in two ways:

and. find it indexand use $splice:

index = todos.findIndex((t) => { return(t.id === id) });
newtodos = update(todos, { $splice: [[index, 1]] })

OR

b. use filter:

newtodos = todos.filter((t) => { return(t.id === id) });

filteris more concise, but I'm not sure if it has any flaws compared to using $splicein this case.

+5
1

immutability-helper:

nested collection:

const collection = [1, 2, { todos: [...todos] }];
const newCollection = update(collection, {
  2: {
    todos: {
      $apply: todos => todos.filter(t => t.id !== id)
    }
  }
});

collection collection[2]:

console.log(newCollection === collection, newCollection[2] === collection[2]);
//false false

, react-redux, connect , , , .

:

const todoList = collection[2].todos;
const idx = todoList.findIndex(t => t.id === id);
const newTodoList = update(todoList, { $splice: [[index, 1]] });
const newCollectionTwo = [...collection];
newCollectionTwo[2] = {
  todos: newTodoList
};

:

console.log(collection, newCollectionTwo, collection === newCollectionTwo, collection[2] === newCollectionTwo[2]); 

, , filter.

, , .

+1

Source: https://habr.com/ru/post/1671500/


All Articles