Add values in array using javascript

    By: Manu
    2 years ago

    Today we are going to see how we can insert data in array using Javascript.

    So here we have an array


    let players = [
                'Rom', 
                'Roger',
                'Andrew',
                'Mark',
                'Albert',
                'John',
                'Steve',
                'Jack'
                ];
    


    Add value in array at the beginning of array


    For that we can use javascript function "unshift", Here is how we do it

    // Add values in the start of array
    
    players.unshift('Manu','Jacky','Tom');
    


    So output will look something like this

    Manu, Jacky, Tom, Rom, Roger, Andrew, Mark, Albert, John, Steve, Jack, 
    


    Now let's see how we can


    Add data at the end of array


    In this case we use javascript function "push" like this

    // Add value in the end of this array
    
    players.push('Manu','Jacky','Tom');
    


    Output will have names printed like this

    Rom, Roger, Andrew, Mark, Albert, John, Steve, Jack, Manu, Jacky, Tom, 
    


    Now what if you want to add data in the middle after some specific value. In this case we use another javascript function "splice". Here is how

    Let's say we need to add value after "Roger" in given array, The to add data there we need to check where "Roger" value present in array(At what index). We can find location of value in array using javascript function "indexOf". Here is How

    players.indexOf('Roger');
    
    // It will return 1  as Roger is in array at 2nd value(Note: array index start from 0). So 
    // name "Rom" is at index 0 and "Roger" is at index 1
    

    Now we use "splice method"

    Here

    let NewNames = ['Manu','Jacky','Tom'];
    
    // players.splice(1st argument, 2nd Argument, 3rd Argument);
    
    players.splice(players.indexOf('Roger')+1, 2, NewNames);
    
    


    1st argument is (Index where you want to insert data)

    2nd Argument is How many values to remove Before inserting new values

    2rd Argument is array of data that needs to be inserted.

    That is it in this example output will have names listed like this

    Rom, Roger, Manu,Jacky,Tom, Albert, John, Steve, Jack, 
    

    Note: we passed 2nd argument as "2", Which is why we do not have "Andrew and Mark" in output.

    Also Note:

    we are adding 1 to "players.indexOf('Roger')". because array index starts from 0.

    So name " Rom" is saved at 0 index.

    And

    Name "Roger" is saved at 1 index.

    And if we want to insert values after "Roger" we need to "+1" to "players.indexOf('Roger')" as

    "players.indexOf('Roger')" returns 1. Index value of "Roger".

    Hope this helps