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?

2667

If the user wants to add an item to an array, but you don't want to append an item at the end or start of the array. You want to directly allow for the insertion of an element at a particular place (index) of the array.

Note:

Array indexes start from 0, so if you want to add the item first, you'll use index 0, in the second place the index is 1, and so on.

We can use it for the for-loop method to do this. But we are using the splice() method of an array to perform this type of operation.

Using array.splice():

The array.splice() method is used to add or remove items from an array. This JavaScript method splice() takes 3 or more arguments,

  • The first is the start index, the index where the element id is to be inserted.
  • The second is the delete count parameter, the number of items to be deleted, and the new items which are to be inserted.
  • This allows to only insert the specified item at a particular index with no deletion.

Program:

<!DOCTYPE html>
<html>
<head> 
  <title>
  How to insert an item into an array at a specific index in JavaScript?
</title>
</head>
<body>
<h1>
  insert an item into an array at a specific index.
</h1>
  <p>The original array is: 10, 11, 12, 13, 14</p>
  <p>Click on the button to insert 55 at index  3</p>
  <p>The new array look like this: <span class="outputnew"></span>
 </p>
  <button onclick="insertElement()">Insert element</button>
  <script type="text/javascript">
   function insertElement() {
    let arr = [10, 11, 12, 13, 14];
    let index = 3;
    let element = 55;

    arr.splice(index, 0, element);
    document.querySelector('.outputnew').textContent =
    arr;
    }
  </script>
</body> 
</html>

Output: Before Click on Button

Output: After Click on Button



Best WordPress Hosting


Share:


Discount Coupons

Get a .COM for just $6.98

Secure Domain for a Mini Price



Leave a Reply


Comments
    Waiting for your comments