Search code examples
javascriptconcatenationsplice

How to add a value to an array without the splice method and overwriting the element? javascript


Is there a way to concat an array at a specific index without overwriting the element, not using the splice method? I usually see concats happen in the beginning or end of an array.

Below is an example of using splice to concat an array at an index

var colors=["red","blue"];
var index=1;

//if i wanted to insert "white" at index 1
colors.splice(index, 0, "white");   //colors =  ["red", "white", "blue"]
```

Solution

  • You could take Array#copyWithin with some adjustments.

    const
        colors = ["red", "blue"],
        index = 1,
        value = "white";
    
    colors.length++;                      // create space for moving
    colors.copyWithin(index + 1, index);  // move values to right
    colors[index] = value;                // add new value
    
    console.log(colors); // ["red", "white", "blue"]