Array.splice() is a JavaScript method that modifies an array in place by removing, replacing, or adding elements. It changes the original array and returns an array of the removed elements (or an empty array if none were removed).
Key Features
Mutating: Directly alters the original array.
Flexible Operations: Can remove elements, insert new ones, or replace existing elements in a single call.
Returns Removed Elements: The method returns an array containing the deleted elements, or an empty array if no elements were removed.
Syntax
array.splice(startIndex, deleteCount, item1, item2, ..., itemN)startIndex: Zero-based index where changes begin. Can be negative to count from the end.deleteCount: Number of elements to remove. If omitted, removes all elements fromstartIndexto the end.item1, item2, ...: Elements to add to the array starting atstartIndex. IfdeleteCountis 0, these are inserted without removing anything.
Examples
Insert at the beginning:
const arr = [1, 2, 3]; arr.splice(0, 0, 0); // [0, 1, 2, 3]Insert at the end:
arr.splice(arr.length, 0, 4); // [0, 1, 2, 3, 4]Replace an element:
arr.splice(1, 1, 'X'); // [0, 'X', 2, 3, 4]Remove elements:
const removed = arr.splice(2, 2); // removed = [2, 3], arr = [0, 'X', 4]
Important Notes
Negative indices count backward from the end of the array.
deleteCountof 0 means no removals, only insertion.Returns an array of removed elements; use
slice()if you want a copy without mutation.Not suitable for strings, as they are immutable.
For non-mutating alternatives, use toSpliced() (ES2022+) to create a new array with changes.
Help with splicing an array into another
php - array_splice() for associative arrays - Stack Overflow
JavaScript Array splice vs slice - Stack Overflow
Why does array.splice(); works like it works? WHY?
Videos
I think you need to do that manually:
# Insert at offset 2
$offset = 2;
$newArray = array_slice($oldArray, 0, $offset, true) +
array('texture' => 'bumpy') +
array_slice($oldArray, $offset, NULL, true);
Based on soulmerge's answer I created this handy function:
function array_insert($array,$values,$offset) {
return array_slice($array, 0, $offset, true) + $values + array_slice($array, $offset, NULL, true);
}
splice() changes the original array whereas slice() doesn't but both of them returns array object.
See the examples below:
var array=[1,2,3,4,5];
console.log(array.splice(2));
This will return [3,4,5]. The original array is affected resulting in array being [1,2].
var array=[1,2,3,4,5]
console.log(array.slice(2));
This will return [3,4,5]. The original array is NOT affected with resulting in array being [1,2,3,4,5].
Below is simple fiddle which confirms this:
//splice
var array=[1,2,3,4,5];
console.log(array.splice(2));
//slice
var array2=[1,2,3,4,5]
console.log(array2.slice(2));
console.log("----after-----");
console.log(array);
console.log(array2);
Splice and Slice both are Javascript Array functions.
Splice vs Slice
The splice() method returns the removed item(s) in an array and slice() method returns the selected element(s) in an array, as a new array object.
The splice() method changes the original array and slice() method doesn’t change the original array.
The splice() method can take n number of arguments and slice() method takes 2 arguments.
Splice with Example
Argument 1: Index, Required. An integer that specifies at what position to add /remove items, Use negative values to specify the position from the end of the array.
Argument 2: Optional. The number of items to be removed. If set to 0(zero), no items will be removed. And if not passed, all item(s) from provided index will be removed.
Argument 3…n: Optional. The new item(s) to be added to the array.
var array=[1,2,3,4,5];
console.log(array.splice(2));
// shows [3, 4, 5], returned removed item(s) as a new array object.
console.log(array);
// shows [1, 2], original array altered.
var array2=[6,7,8,9,0];
console.log(array2.splice(2,1));
// shows [8]
console.log(array2.splice(2,0));
//shows [] , as no item(s) removed.
console.log(array2);
// shows [6,7,9,0]
Slice with Example
Argument 1: Required. An integer that specifies where to start the selection (The first element has an index of 0). Use negative numbers to select from the end of an array.
Argument 2: Optional. An integer that specifies where to end the selection but does not include. If omitted, all elements from the start position and to the end of the array will be selected. Use negative numbers to select from the end of an array.
var array=[1,2,3,4,5]
console.log(array.slice(2));
// shows [3, 4, 5], returned selected element(s).
console.log(array.slice(-2));
// shows [4, 5], returned selected element(s).
console.log(array);
// shows [1, 2, 3, 4, 5], original array remains intact.
var array2=[6,7,8,9,0];
console.log(array2.slice(2,4));
// shows [8, 9]
console.log(array2.slice(-2,4));
// shows [9]
console.log(array2.slice(-3,-1));
// shows [8, 9]
console.log(array2);
// shows [6, 7, 8, 9, 0]
Hello,
so in my honest opinion the Array.prototype.splice makes no sense to me. Why didn't they just add a nice method like "remove" "update" "swap" instead of "splice"? Who's thinking of those stupid names and why did they put all 3 "functions" into this one method?
I've created my own "remove from array" method:
Array.prototype.remove = function(value){
var index = this.indexOf(value);
this.splice(index,1);
}EDIT;
I found something on stack overflow.
https://stackoverflow.com/questions/6515385/alternate-method-to-splice-function-in-javascript
Array.prototype.remove = function(value, deleteCount) {
var start = array.indexOf(value);
var result = [];
var removed = [];
var argsLen = arguments.length;
var arrLen = this.length;
var i, k;
// Follow spec more or less
deleteCount = parseInt(deleteCount, 10);
// Deal with negative start per spec
// Don't assume support for Math.min/max
if (start < 0) {
start = arrLen + start;
start = (start > 0)? start : 0;
} else {
start = (start < arrLen)? start : arrLen;
}
// Deal with deleteCount per spec
if (deleteCount < 0) deleteCount = 0;
if (deleteCount > (arrLen - start)) {
deleteCount = arrLen - start;
}
// Copy members up to start
for (i = 0; i < start; i++) {
result[i] = this[i];
}
// Add new elements supplied as args
for (i = 3; i < argsLen; i++) {
result.push(arguments[i]);
}
// Copy removed items to removed this
for (i = start; i < start + deleteCount; i++) {
removed.push(this[i]);
}
// Add those after start + deleteCount
for (i = start + (deleteCount || 0); i < arrLen; i++) {
result.push(this[i]);
}
// Update original this
this.length = 0;
i = result.length;
while (i--) {
this[i] = result[i];
}
// Return this of removed elements
return removed;
}You can use apply to avoid eval:
var args = [start, number].concat(newItemsArray);
Array.prototype.splice.apply(theArray, args);
The apply function is used to call another function, with a given context and arguments, provided as an array, for example:
If we call:
var nums = [1,2,3,4];
Math.min.apply(Math, nums);
The apply function will execute:
Math.min(1,2,3,4);
UPDATE: ES6 version
If you're coding in ES6, you can use the "spread operator" (...).
array.splice(index, 0, ...arrayToInsert);
To learn more about the spread operator see the MDN documentation.
The 'old' ES5 way
If you wrap the top answer into a function you get this:
function insertArrayAt(array, index, arrayToInsert) {
Array.prototype.splice.apply(array, [index, 0].concat(arrayToInsert));
}
You would use it like this:
var arr = ["A", "B", "C"];
insertArrayAt(arr, 1, ["x", "y", "z"]);
alert(JSON.stringify(arr)); // output: A, x, y, z, B, C
You can check it out in this jsFiddle: http://jsfiddle.net/luisperezphd/Wc8aS/