There are really creative answers to this question. Here is a simple solution for those who are just starting with arrays. If desired, it can be made to work for browsers compatible with ECMAScript 3.
Know something about splicing before you begin.
Mozilla Developer Network: Array.prototype.splice ()
First, understand the two important forms of .splice() .
let a1 = [1,2,3,4], a2 = [1,2];
Method 1) Delete elements x (deleteCount), starting from the desired index.
let startIndex = 0, deleteCount = 2; a1.splice(startIndex, deleteCount);
Method 2) Remove the elements after the desired starting index to the end of the array.
a1.splice(2); // returns [3,4], a1 would be [1,2]
Using .splice() , the goal may be to split a1 into the head and tail arrays using one of the two forms above.
Using method # 1, the return value will become the head, and a1 tail.
let head = a1.splice(startIndex, deleteCount);
Now in one fell swoop connect the head, body ( a2 ) and tail
[].concat(head, a2, a1);
Thus, this solution is more like the real world than any other presented so far. Isn't that what you would do with Legos? ;-) Here is a function executed using method # 2.
function insertArray(target, body, startIndex) { let tail = target.splice(startIndex);
In short:
function insertArray(target, body, startIndex) { return [].concat(target, body, target.splice(startIndex)); }
safer:
function insertArray(target, body, startIndex) { const ARRAY_START = 0, ARRAY_END = target.length - 1, ARRAY_NEG_END = -1, START_INDEX_MAGNITUDE = Math.abs(startIndex); if (startIndex === ARRAY_START) { throw new Error("The value for startIndex cannot be zero (0)."); } if (startIndex === ARRAY_END || startIndex === ARRAY_NEG_END) { throw new Error("The startIndex cannot be equal to the last index in target, or -1."); } if (START_INDEX_MAGNITUDE >= ARRAY_END) { throw new Error("The absolute value of startIndex must be less than the last index."); } return [].concat(target, body, target.splice(startIndex)); }
Benefits of this solution include:
1) A simple premise dominates the solution - fill in an empty array.
2) The head, body and tail nomenclature feels natural.
3) There is no double call .slice() . No slicing at all.
4) No .apply() . Very unnecessary.
5) The chaining method is avoided.
6) Works in ECMAScript 3 and 5 just using var instead of let or const .
** 7) Ensures that the head and tail will smack over the body, unlike many other solutions presented. If you add an array before or after the borders, you should at least use .concat() !!!!
Note. Using a distribution operator ... makes it all a lot easier.