JavaScript Array Splice() – add / remove values at any position

Total
0
Shares
javascript array splice() add remove values auto adjusting size
Table of Contents Hide
  1. Use cases and examples of splice()

To add or remove values from any position of an array in JavaScript, we can use splice() function. Here is the code –

var arr = ["item 1", "item 2", "item 3", "item 4"];
arr.splice(index where item to be added or removed, number of items to remove);

This function has 2 required parameters and all other are optional. These parameters are –

  1. Index – (Required) The first parameter is the index where you want to add new items or remove items from that index.
  2. Number of items – (Required) Second parameter is the number of items you want to remove from given index.
  3. items – (Optional) These are comma separated list of items which you want to add in your array at the index.

You may also like –

Use cases and examples of splice()

Suppose the given array is –

var arr = ["item 1", "item 2", "item 3", "item 4"];
Example 1 – You want to remove 3rd item

3rd item means, array index 2, because indexes starts from 0. Use splice() like this –

arr.splice(2, 1);

First parameter is index so we used 2 and second parameter is number of items so we used 1. Our final array will become –

["item 1", "item 2", "item 4"];
Example 2 – You want to add 2 items at 3rd position

It means you want to add 2 items (let’s say – item 5 and item 6) at 2nd index of array. You should use the function like this –

arr.splice(2, 0, "item 5", "item 6");

You can see that we have used 0 as second parameter. This is because we do not want to remove any item. We just want to add two new items at index 2.

Final array will appear like this –

["item 1", "item 2", "item 5", "item 6", "item 3", "item 4"];
Example 3 – Removing 2nd and 3rd item and adding 4 items at their place

Removing 2nd and 3rd item = removing 2 items from 1st index.

Let’s say we want to add these 4 items – new item 1, new item 2, new item 3, new item 4.

So, final array should look like this –

["item 1", "new item 1", "new item 2", "new item 3", "new item 4", "item 4"];

Use splice() in this way –

arr.splice(1, 2, "new item 1", "new item 2", "new item 3", "new item 4");

Note: splice() can only remove consecutive items. Like you can’t remove 2nd and 4th item. But you can remove 2nd, 3rd and 4th item.

This is because function takes initial index and number of items to remove.

      I learned array splice() in Javascript ♥♥

Click here to Tweet this

Sign Up for Our Newsletters

Get only the best articles delivered to your mail

You May Also Like
threejs - installation creating a scene

Getting started with three.js

Table of Contents Hide Introduction to three.jsInstallationCreating a SceneCreating a cameraCreating a rendererLive DemoLoading 3d Models In this article I am going to show you how you can get started…
View Post