I'm currently attempting to implement JavaScript's version of Python's insert at index functionality.
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);
The above code snippet results in:
[ 0, 4, 1, 3, 2, <5 empty items> ]
However, if I use the following code instead:
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 time, it yields:
[ 0, 4, 1, 3, 2 ]
Why is there a difference between the two outputs? The second output is actually the desired one.