How to Add Element at Index into an Array in Javascript?

Aug 30, 2022 . Admin



Hello dev,

This example is focused on how to add an element at index into an array in javascript. In this article, we will implement how to add the item to an array at a specific index in javascript. This article goes into detail on adding elements at the index of the array in javascript.

To perform this operation you will use the splice() method of an array. This function is very powerful and in addition to the use we’re going to make now, it also allows us to delete items from an array. So, proceed with caution.

So, let's see bellow solution:

Example: 1
index.html
<!DOCTYPE html>
<html>
    <head>
        <title>How to Add Element at Index into an Array in Javascript? - MyWebtuts.com</title>
    </head>
    <body>
        <h1>How to Add Element at Index into an Array in Javascript? -  MyWebtuts.com</h1>
        
        <script type="text/javascript">
            const colors = ['yellow', 'red'];
            colors.splice(1, 0, 'blue');

            //Give output on the console
            console.log(colors);
        </script>
    </body>
<html>
Output:
['yellow', 'blue', 'red', 'green']
Example: 2 index.html
<!DOCTYPE html>
<html>
    <head>
        <title>How to Add Element at Index into an Array in Javascript? - MyWebtuts.com</title>
    </head>
    <body>
        <h1>How to Add Element at Index into an Array in Javascript? -  MyWebtuts.com</h1>
        
        <script type="text/javascript">
            const fruits = ['mango','banana','orange'];
            fruits.splice(1, 0, 'graps','apple');

            //Give output on the console
            console.log(fruits);
        </script>
    </body>
<html>
Output:
['mango', 'graps', 'apple', 'banana', 'orange']
I hope it will help you...
#Javascript