vignesh selvarathinam vignesh selvarathinam - 23 days ago 8
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();
fruits.push("Kiwi",pop);
document.getElementById("demo").innerHTML = fruits;
}

<!DOCTYPE html>
<html>
<body>

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

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

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

</body>
</html>





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
Answer

Use splice method for it. see fiddle

fruits.splice(index, 0, item); 

will insert item into fruits array at the specified index