Remove from array

2 snippets across 2 stacks — JavaScript, React

JSJavaScript

Adding and Removing Elements

JS · Arrays
syntax
arr.push(item)    // end
arr.pop()         // end
arr.unshift(item) // start
arr.shift()       // start
arr.splice(index, deleteCount, ...items)
example
const tasks = ["code", "test"];
tasks.push("deploy");       // ["code", "test", "deploy"]
tasks.unshift("plan");      // ["plan", "code", "test", "deploy"]
const removed = tasks.pop(); // "deploy"

// Insert at index 2
tasks.splice(2, 0, "review");
console.log(tasks); // ["plan", "code", "review", "test"]

Note push/pop are O(1). unshift/shift are O(n) because all indices must be renumbered. splice() mutates the original array.

REReact

Arrays in State

RE · useState
syntax
// Add
setItems(prev => [...prev, newItem]);
// Remove
setItems(prev => prev.filter(i => i.id !== id));
// Update one
setItems(prev => prev.map(i => i.id === id ? { ...i, done: true } : i));
example
function TodoList() {
  const [todos, setTodos] = useState([]);
  const [text, setText] = useState('');

  function addTodo() {
    if (!text.trim()) return;
    setTodos(prev => [
      ...prev,
      { id: crypto.randomUUID(), text, done: false },
    ]);
    setText('');
  }

  function removeTodo(id) {
    setTodos(prev => prev.filter(t => t.id !== id));
  }

  function toggleTodo(id) {
    setTodos(prev =>
      prev.map(t => t.id === id ? { ...t, done: !t.done } : t)
    );
  }

  return (
    <div>
      <input value={text} onChange={e => setText(e.target.value)} />
      <button onClick={addTodo}>Add</button>
      <ul>
        {todos.map(t => (
          <li key={t.id}>
            <span
              style={{ textDecoration: t.done ? 'line-through' : 'none' }}
              onClick={() => toggleTodo(t.id)}
            >
              {t.text}
            </span>
            <button onClick={() => removeTodo(t.id)}>Remove</button>
          </li>
        ))}
      </ul>
    </div>
  );
}

Note Use filter to remove, map to update, and spread to add. Never use push, splice, or direct index assignment on state arrays -- those mutate the existing array instead of creating a new one.