Skip to content

Instantly share code, notes, and snippets.

@charlesroper
Last active April 27, 2023 10:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save charlesroper/aa744fec8dd8c2098513820ce4cd2e94 to your computer and use it in GitHub Desktop.
Save charlesroper/aa744fec8dd8c2098513820ce4cd2e94 to your computer and use it in GitHub Desktop.
Examples of Array.prototype.with()

Here are some more creative uses for the Array.prototype.with() method:

  • Creating a new array with a different value at a random index. This can be useful when you want to simulate a random change in an array.
const arr = [1, 2, 3, 4, 5];
const randomIndex = Math.floor(Math.random() * arr.length);
const randomValue = Math.floor(Math.random() * 10);
const withRandom = arr.with(randomIndex, randomValue);
console.log(withRandom); // e.g. [1, 2, 7, 4, 5]
  • Creating a new array with a value swapped with another value. This can be useful when you want to reorder some elements in an array.
const arr = ["a", "b", "c", "d", "e"];
const swap = (arr, i, j) => {
  return arr.with(i, arr[j]).with(j, arr[i]);
};
const withSwap = swap(arr, 1, 3);
console.log(withSwap); // ["a", "d", "c", "b", "e"]
  • Creating a new array with a value inserted at a specific index. This can be useful when you want to add an element to an array without changing its length.
const arr = [1, 2, 3, 4];
const insert = (arr, index, value) => {
  return arr.with(index - 1, [arr[index - 1], value]).flat();
};
const withInsert = insert(arr, 2, "a");
console.log(withInsert); // [1, "a", 2, 3, 4]

Source: Conversation with Bing, 27/04/2023

(1) Array.prototype.with() - JavaScript | MDN - Mozilla Developer. https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array/with.

(2) Array.prototype - JavaScript | MDN. http://www.devdoc.net/web/developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/prototype.html.

(3) JavaScript Array prototype Constructor - W3School. https://www.w3schools.com/jsref/jsref_prototype_array.asp.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment