JavaScript Array splice() method

The splice() method can be used to remove items from anywhere in an array. In this example, we use the splice() method to remove the items at indexes 1 and 2 (the “green” and “blue” items) from the array. This leaves us with an array that no longer contains those items.

The splice() method returns an array containing the removed items, so we can use this to get the removed items and do something with them if needed.

// create an array with some items
const colors = ["red", "green", "blue", "yellow", "orange", "pink"];

// remove items from the middle of the array
const removedColors = colors.splice(1, 2);

// print the array
console.log(colors);  // Output: ["red", "blue", "yellow", "orange", "pink"]

// print the removed items
console.log(removedColors);  // Output: ["green", "blue"]

Here is another example of using the splice() method to add items to an array:

// create an array with some items
const colors = ["red", "green", "blue"];

// add items to the middle of the array
const addedColors = colors.splice(1, 0, "yellow", "orange", "pink");

// print the array
console.log(colors);  // Output: ["red", "yellow", "orange", "pink", "green", "blue"]

// print the added items
console.log(addedColors);  // Output: []

In this example, we use the splice() method to add the “yellow”, “orange”, and “pink” items to the array at index 1. Since we are not removing any items, the splice() method returns an empty array.

The splice() method is a versatile method that can be used to add or remove items from anywhere in an array. It can be useful for modifying an array in-place, or for creating a new array from an existing array.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: