7.2 Examples: updating an Array destructively and non-destructively

The following code shows a function that updates Array elements destructively and uses it on an Array.

  1. function setElementDestructively(arr, index, value) {
  2. arr[index] = value;
  3. }
  4. const arr = ['a', 'b', 'c', 'd', 'e'];
  5. setElementDestructively(arr, 2, 'x');
  6. assert.deepEqual(arr, ['a', 'b', 'x', 'd', 'e']);

The following code demonstrates non-destructive updating of an Array:

  1. function setElementNonDestructively(arr, index, value) {
  2. const updatedArr = [];
  3. for (const [i, v] of arr.entries()) {
  4. updatedArr.push(i === index ? value : v);
  5. }
  6. return updatedArr;
  7. }
  8. const arr = ['a', 'b', 'c', 'd', 'e'];
  9. const updatedArr = setElementNonDestructively(arr, 2, 'x');
  10. assert.deepEqual(updatedArr, ['a', 'b', 'x', 'd', 'e']);
  11. assert.deepEqual(arr, ['a', 'b', 'c', 'd', 'e']);

.slice() and spreading make setElementNonDestructively() more concise:

  1. function setElementNonDestructively(arr, index, value) {
  2. return [
  3. ...arr.slice(0, index), value, ...arr.slice(index+1)];
  4. }

Both versions of setElementNonDestructively() update shallowly: They only change the top level of an Array.