vignesh selvarathinam vignesh selvarathinam - 4 months ago 39
AngularJS Question

How to push the values in array based on position?

I am working on pushing the values in array.

My Exact Scenario:

If the array contains 2 values, after the push operation the pushed value has to come in between the 2 values(which is based on position).

I somehow did it using Pop the last value and Push the new value with poped value. Below is My code.

var fruits = ["Banana", "Mango"];
document.getElementById("demo").innerHTML = fruits;

function myFunction() {
var pop = fruits.pop();
document.getElementById("demo").innerHTML = fruits;

<!DOCTYPE html>

<p>Click the button to add a new element to the array.</p>

<button onclick="myFunction()">Try it</button>

<p id="demo"></p>


My code is Working Fine.But is there any better solution for that using Push method only (without using pop).

Thanks in advance.

pD7 pD7

Use splice method for it. see fiddle

fruits.splice(index, 0, item); 

will insert item into fruits array at the specified index