From 1793aec2eccdd420a5c284b3748e521d2a263d5f Mon Sep 17 00:00:00 2001 From: Angelos Chalaris Date: Fri, 22 May 2020 09:07:35 +0300 Subject: [PATCH] Add insertAt --- snippets/insertAt.md | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) create mode 100644 snippets/insertAt.md diff --git a/snippets/insertAt.md b/snippets/insertAt.md new file mode 100644 index 000000000..59fa67bda --- /dev/null +++ b/snippets/insertAt.md @@ -0,0 +1,23 @@ +--- +title: insertAt +tags: array,intermediate +--- + +Mutates the original array to insert the given values at the specified index. + +Use `Array.prototype.splice()` with an appropriate index and a delete count of `0`, spreading the given values to be inserted. + +```js +const insertAt = (arr, i, ...v) => { + arr.splice(i + 1, 0, ...v); + return arr; +}; +``` + +```js +let myArray = [1, 2, 3, 4]; +insertAt(myArray, 2, 5); // myArray = [1, 2, 3, 5, 4] + +let otherArray = [2, 10]; +insertAt(otherArray, 0, 4, 6, 8); // otherArray = [2, 4, 6, 8, 10] +```