Immutability
In Javascript whether a value passed by reference depends on it's type.
Strings and numbers are passed by value.
Objects (including arrays) are passed by reference.
Object.assign
{...obj, obj2}
[...arr, obj]
.filter()
.slice and .splice
.splice() — mutates the array directly, which makes it somewhat unhealthy to use in React, unless you go through the trouble of cloning the array beforehand.
.slice() — good, does not mutate the array directly, returns shallow clone of the array. Important to remember that if items are objects, they will not be cloned by .slice()
Removing item from an array
// ES6+
items: [
...items.slice(0, i),
...items.slice(i + 1)
],
// by index
const items = ['a', 'b', 'c', 'd', 'e', 'f']
const i = 2
const filteredItems = items.slice(0, i).concat(items.slice(i + 1, items.length))
// ["a", "b", "d", "e", "f"]
// If you know the value
const items = ['a', 'b', 'c', 'd', 'e', 'f']
const valueToRemove = 'c'
const filteredItems = items.filter(item => item !== valueToRemove)
// ["a", "b", "d", "e", "f"]
// by index wit removeItem function
const items = ['a', 'b', 'c', 'd', 'e', 'f']
const removeItem = (items, i) => items.slice(0, i-1).concat(items.slice(i, items.length))
let filteredItems = removeItem(items, 3)
filteredItems = removeItem(filteredItems, 5)
//["a", "b", "c", "d"]