50% off all plans with SPRING50
js Advanced

Immutable add, edit, delete operations

Immutable add, edit, delete operations
Photo by George Becker on Pexels
Array CRUD Operations
Interactive editor — edit code and see live results Open in Editor

Immutability with rest spread operator

let items = [];

// Add item to the beginning of items array using rest operator
const addItemToStart = (newItem) => {
  items = [newItem, ...items];
}

// Add item to the end of items array using rest operator
const addItemToEnd = (newItem) => {
  items = [...items, newItem];
}

// Edit item using .map method, if id matches, use rest operator to override
// item properties with updatedItem, otherwise return item as is
const editItem = (updatedItem) => {
  items = items.map((item) => {
    if (updatedItem.id === item.id) {
      return {
        ...item,
        ...updatedItem
      }
    }

    return item;
  })
}

// Delete item using .filter method, if id matches, delete it from items array
const deleteItem = (idToRemove) => {
  items = items.filter((item) => item.id !== idToRemove);
}

Summary

  • Rest spread operator is helpful when it comes to working with arrays and objects.
  • Add, edit, delete functions can be used on any object structure and should work well with the array of those objects.

Try this in our interactive code editor

Practice hands-on with our built-in code sandbox.

Open Code Editor
Adrian Bigaj
Adrian Bigaj

Creator of BigDevSoon

Full-stack developer and educator passionate about helping developers build real-world skills through hands-on projects. Creator of BigDevSoon, a vibe coding platform with 21 projects, 100 coding challenges, 40+ practice problems, and Merlin AI.