Add to array

3 snippets across 3 stacks — Bash & Linux, JavaScript, React

SHBash & Linux

Arrays

SH · Bash Scripting
syntax
arr=(val1 val2 val3)
${arr[0]}  ${arr[@]}  ${#arr[@]}
example
SERVERS=("web01.prod" "web02.prod" "db01.prod")
echo "First: ${SERVERS[0]}"
echo "All: ${SERVERS[@]}"
echo "Count: ${#SERVERS[@]}"

SERVERS+=("cache01.prod")

for srv in "${SERVERS[@]}"; do
  ssh deploy@"${srv}" 'uptime'
done
output
First: web01.prod
All: web01.prod web02.prod db01.prod
Count: 3

Note Indices start at 0. Always quote "${arr[@]}" to preserve elements with spaces. ${#arr[@]} gives the length. += appends. unset 'arr[1]' removes an element (but does not reindex). Bash arrays are not available in sh/POSIX shell.

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.