user2557504 user2557504 - 1 year ago 246
jQuery Question

How to swap data in an array using splice

I have a small problem. I am simply trying to swap the data in the array. I am using splice but its still keeping 1 element there at the end. How do I fully replace the data that is currently there without retaining the other?

fruits.splice(0, 1, "Lemon", "Kiwi");
document.getElementById("demo").innerHTML = fruits;

var fruits = ["Banana", "Orange"];

var col1 = ["Banana", "Orange","pies","pretzels"];
var col2 = ["Banana", "Orange"];
document.getElementById("demo").innerHTML = fruits;

<script src=""></script>
<p>Click the button to add and remove elements.</p>

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

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

Answer Source

Set the delete count as array length.

fruits.splice(0, fruits.length, "Lemon", "Kiwi");
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download