This page looks best with JavaScript enabled

Add An Item To An Array Using JavaScript Splice()

 ·  ☕ 2 min read  ·  ✍️ Adesh

JavaScript Splice() Syntax

Here is the Splice() method syntax.

Splice() method’s parameters Description

  • start –– this is the position where an item will insert. This is required.
  • count –– how many items you want to remove. If it is set to 0, no item will remove. This is optional.
  • items –– comma-separated list of items you want insert at a specific position.
Note: Before adding an element to an array, we must know about its index position. Each array start with an index 0.

Insert an item at the beginning of an array using Splice()

We will insert an item at the first position, i.e.index 0.

1
2
3
var array = ['two', 'three', 'four'];
array.splice(0,0,'one');
// the result array is ['one', 'two', 'three', 'four']

Insert an item at a specific index of an array using Splice()

We want to insert an item at 2nd position i.e. index 1.

1
2
3
var array = ['red','green', 'yellow', 'blue'];
array.splice(1,0, 'pink');
// the result array is ['red','pink','green','yellow','blue']

Insert multiple items in an array

Now, we want to insert multiple colors in the above array.

1
2
3
var array = ['red','green', 'yellow', 'blue'];
array.splice(1,0,'pink','gray','orange')
// the result array is ['red','pink', 'gray', 'orange','green', 'yellow', 'blue']

Start is greater than the length of an array

If the start index of the inserting item is greater than the length of an array. The start will be set to the length of the array.

1
2
3
var array = ['red','green','yellow'];
array.splice(5,0,'orange');
// the result array is ['red','green','yellow','orange'];

Start is negative

If negative, it will begin that many elements from the end of the array (with origin -1, meaning -n is the index of the nth last element and is therefore equivalent to the index of array.length - n)

1
2
3
var array = \['red','green','yellow'];
array.splice(-1,0,'orange');
// the result array is ['red','green','orange','yellow'];

Reference: developer.mozilla.org

Conclusion

We learned about various methods of inserting an item in an array using Splice() method. I hope you enjoyed this post.

Further Reading

Understanding Angular Modules and Its Types

Create Your Blog Site With Gatsby.js Static Site Generator

Sharing Files Anonymously Online Via OnionShare

Array.Prototype.Flat() or ES2019 Array Flat() function

Type Inference In TypeScript

Share on

Adesh
WRITTEN BY
Adesh
Technical Architect