Return a new array with one changed position.

update-array `map` can create a new array with one position changed. The original values are read, not edited in place.

Updating Arrays

index
update_array.js
Replay: real traced execution (multi-file project)
const index = 1;
const updated = [10, 20, 30]
  .map((value, i) => (i === index ? value + 1 : value))
  .join(",");
const changed = "index=" + index;

console.log("updated=" + updated);
console.log("changed=" + changed);
const index = 0;
const updated = [10, 20, 30]
  .map((value, i) => (i === index ? value + 1 : value))
  .join(",");
const changed = "index=" + index;

console.log("updated=" + updated);
console.log("changed=" + changed);
const index = 2;
const updated = [10, 20, 30]
  .map((value, i) => (i === index ? value + 1 : value))
  .join(",");
const changed = "index=" + index;

console.log("updated=" + updated);
console.log("changed=" + changed);
  1. index ← 1, updated ← 10,21,30, changed ← index=1

    1const index→ 1 = 1; //@index=0, 22const updated→ 10,21,30 = [10, 20, 30]3  .map((value, i) => (i === index ? value + 1 : value))4  .join(",");5const changed→ index=1 = "index=" + index1;67console.log("updated=" + updated10,21,30);8console.log("changed=" + changedindex=1);
    outputupdated=10,21,30
    changed=index=1
  1. index ← 0, updated ← 11,20,30, changed ← index=0

    1const index→ 0 = 0;2const updated→ 11,20,30 = [10, 20, 30]3  .map((value, i) => (i === index ? value + 1 : value))4  .join(",");5const changed→ index=0 = "index=" + index0;67console.log("updated=" + updated11,20,30);8console.log("changed=" + changedindex=0);
    outputupdated=11,20,30
    changed=index=0
  1. index ← 2, updated ← 10,20,31, changed ← index=2

    1const index→ 2 = 2;2const updated→ 10,20,31 = [10, 20, 30]3  .map((value, i) => (i === index ? value + 1 : value))4  .join(",");5const changed→ index=2 = "index=" + index2;67console.log("updated=" + updated10,20,31);8console.log("changed=" + changedindex=2);
    outputupdated=10,20,31
    changed=index=2