I am trying to replicate Python's insert at index functionality in Javascript.
var index = [0,1,2,3,4]
var nums = [0,1,2,2,1]
const target = new Array(nums.length);
for (let i=0; i<index.length; i++) {
target.splice(nums[i], 0, index[i]);
};
console.log(target);
This produces the following output:
[ 0, 4, 1, 3, 2, <5 empty items> ]
However, if I run the following code:
var index = [0,1,2,3,4]
var nums = [0,1,2,2,1]
const target = [] //new Array(nums.length);
for (let i=0; i<index.length; i++) {
target.splice(nums[i], 0, index[i]);
};
console.log(target);
This produces the following output:
[ 0, 4, 1, 3, 2 ]
What is going on? The second output is the one I desire.