0

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.

finite_diffidence
  • 893
  • 2
  • 11
  • 20

2 Answers2

0

new Array(nums.length) will fill the array with 'empty slots' for that number.

const target = [] Will be [ ]

const target = new Array(5) will be [, , , , ]

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Array More info here.

Nathan
  • 479
  • 6
  • 13
0

when you initialize array like this :

const target = new Array(index.length);

This code will initiate "target" array with five empty box. in result it contain garbage value and it may affect your value after insertion.

But when you initialize like this :

const target = [];

This code will initiate "target" array without defining the size of it.
it means you can insert n number of dynamic value inside this.
('n' denote the size of array)

So always use second option which is good practice to use javascript Array

Aslam khan
  • 315
  • 1
  • 7