user2915962 user2915962 - 2 months ago 11
Javascript Question

add/remove elements in array-like object

I have an array-like object:

[

1:Array[10], 2: Array[2], 3: Array[2], 4: Array[2], 5: Array[3], 6: Array[1]]


Im trying to remove the first two elements, do some stuff, and then insert them again at the same place.

Here is what i do:

array = Array.prototype.splice.call(array, 0,2);


When logging
array
in firefox it show this:

Array [ <2 empty slots>, Array[1], Array[2], Array[3], Array[1] ]


Looks good to me,I removed the first two elements and the array now starts with 2 empty slots.

So now, what I hope to do is to add objects to these 2 empty slots.

For simplicity, lets remove to items from the array and then insert them again at the same place:

var twoFirstItems = Array.prototype.slice.call(array, 0,2);
array = Array.prototype.splice.call(array, 0,2);


Now,to re-insert
twoFirstItems
I would think that I could do:

array.unshift(twoFirstItems)


This does not work as expected, it inserts the array but it does not have a
key
as it had before its modifikation. I assume this has to do with
unshift
not working the same with an
array-like object
as with an
array
.

So how do you remove/insert elements to an
array-like-object
properly?

If i do the following:

console.log(array);
console.log(typeof array);


The result:

Array [ <1 empty slot>, Array[2], Array[2], Array[2], Array[3], Array[1] ]
object

Answer

Without any complications, you can just re-assign the modified array at that index.

var a = [
  [1, 2, 3, 4, 5, 6],
  [1, 2, 3, 4, 5, 6],
  [1, 2, 3, 4, 5, 6],
  [1, 2, 3, 4, 5, 6]

]

a[0] = a[0].map((el) => el * 10)
a[1] = a[1].map((el) => el * 20)

console.log(a)

Comments