javascript insert element into array code example
Example 1: javascript insert item into array
var colors=["red","blue"];
var index=1;
colors.splice(index, 0, "white");
Example 2: array insertion javascript
Array.prototype.insert = function ( index, item ) {
this.splice( index, 0, item );
};
Example 3: how to insert a value into an array javascript
var list = ["foo", "bar"];
list.push("baz");
["foo", "bar", "baz"]
Example 4: javascript add array to array at index
a1.splice(2, 0, ...a2);
Example 5: js add array items to array
var arrayA = [1, 2];
var arrayB = [3, 4];
var newArray = arrayA.concat(arrayB);
Example 6: set element at index javascript array and create new array
const items = [1, 2, 3, 4, 5]
const insert = (arr, index, newItem) => [
...arr.slice(0, index),
newItem,
...arr.slice(index)
]
const result = insert(items, 1, 10)
console.log(result)