# Using JavaScript's Array.splice with assigning the replacements item as an array

I've got to delete / replace elements in an array. For accomplishing these task one usually uses Array.splice().

Problem: Array.splice() expects the replacement items as a comma separated list. But I got the values as an array. I've made this helper function which makes it possible to use splice with an array instead of single values.

    // Deletes elements in an array and
// replaces the elements with other
// values.
// -- Parameter -------------------
// 1. Array - The array from which
// elements shall be deleted.
// 2. Number - The index at which to
// start the deletion.
// 3. Number - The count of elements
// to delete.
// 4. Array - The elements to insert
// into the target array.
// -- Return ----------------------
// Array - The deleted elements.

function replaceArrayElements(
targetArray,
startIndex,
deleteCount,
replacements ) {
// 1. Parameter of .apply():
//   Defining the context (this-keyword).
// 2. Parameter:
//   b.) Delete 3 elements.
//   c.) Put these elements into the array
//   as new values.
//   a.), b.), c.) concated together
//   into one array. The array is then
//   used as the parameters of .splice().
return Array.prototype.splice.apply(
targetArray,
[startIndex, deleteCount].concat(replacements));
}

// -------- TEST ---------------------------------
var test = [];

for (var i = 1; i <= 10; i++) {
test.push(i);
}

console.log('Before insert: %o', test);

var ret =
replaceArrayElements(test, 5, 3, ['Six', 'Seven', 'Eight']);

console.log('After insert: %o', test);
console.log('Return: %o', ret);
// -- RESULTS -----
// Before insert: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
// After insert: [1, 2, 3, 4, 5, "Six", "Seven", "Eight", 9, 10]
// Return: [6, 7, 8]


The function does as expected. But anyway: If someone knows a better way to accomplish the task then please let me know. The same for improvement suggestions.

• You could add a type-check for targetArray and replacements like this: if (Object.prototype.toString.call(targetArray) !== "[object Array]") throw "targetArray is not of the type array!"; Feb 7, 2016 at 10:05

targetArray.splice(start, end, ...replacements);