How to Insert An Item Into An Array At A Specific Index In JavaScript

How to Insert An Item Into An Array At A Specific Index In JavaScript

Here are some tricks to enter data at a specific index in JavaScript

We mostly use the array when we are developing in frontend development. Here are some tricks to enter a value in the array’s specific index in JavaScript.

1. Using the Array Insert method

We can use the Array.insert the method by doing this:

Array.prototype.insert = function ( index, item ) {
    this.splice( index, 0, item );
};

Then you can use it like:

var arr = [ 'data1', 'data2', 'data3', 'data4' ];
arr.insert(2, 'data5');

// => arr == [ 'data1', 'data2', 'data5', 'data3', 'data4' ]

2. Using the Splice method

arr.splice(index, 0, item); will insert item into arr at the specified index (deleting 0 items first, that is, it's just an insert).

Let’s create one example where we want to add data at index 2.

var arr = [];
arr[0] = "abc";
arr[1] = "cde";
arr[2] = "efg";
console.log(arr.join());
arr.splice(2, 0, "newval");
console.log(arr.join());

javascript

What is Geek Coin

What is GeekCash, Geek Token

Best Visual Studio Code Themes of 2021

Bootstrap 5 Tutorial - Bootstrap 5 Crash Course for Beginners

Nest.JS Tutorial for Beginners

Hello Vue 3: A First Look at Vue 3 and the Composition API

Hire Dedicated JavaScript Developers -Hire JavaScript Developers

Hire dedicated JavaScript Developers who are proficient in AngularJS, ReactJS, NodeJS, & VueJS frameworks. Get flexible hiring models as per your business requirements.

What is JavaScript - Stackfindover - Blog

What is PHP: - Who invented PHP, how it works, answers to all such questions about PHP, and much other information, you are going to

JavaScript Shopping Cart - Javascript Project for Beginners

JavaScript Shopping Cart - javascript shopping cart tutorial for beginnersBuy me a coffee 🍺 https://www.paypal.com/paypalme/ziddahSource Code: https://bit....

The essential JavaScript concepts that you should understand

The essential JavaScript concepts that you should understand - For successful developing and to pass a work interview

Learn JavaScript - Full Course for Beginners. DO NOT MISS!!!

In this video tutorial, we'll learn Learn JavaScript - Full Course for Beginners. This complete 134-part JavaScript tutorial for beginners will teach you everything you need to know to get started with the JavaScript programming language. DO NOT MISS!!!