[ES2024] Simplify array immutable changes with the new array.with method

The new Array.with method gives you an immutable syntax for changing values of an array at a specified index.

Sometimes .map will be more efficient. So, in this lesson we'll compare both methods while replacing an object at a specific index.

 

var todos = [
   { id: 1, completed: false, task: "Write a blog post" },
   { id: 2, completed: true, task: "Review pull requests" }
]
var idx = todos.findIndex(item => item.id === 1)
// toggle the completed of todo with the known idx
todos.with(idx, {...todos.at(idx), completed: !todos.at(idx).completed})

 

posted @ 2024-05-22 14:22  Zhentiw  阅读(2)  评论(0编辑  收藏  举报