0

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
8
  • what do you mean by array-like, when you work with an array? Commented Oct 2, 2016 at 14:55
  • Yes, it appears to be an ordinary array but when i do: console.log(typeof array) it logs 'object'. Commented Oct 2, 2016 at 14:56
  • why not use the index of the array? Commented Oct 2, 2016 at 14:58
  • And if you check if it's an array the correct way. what does it say -> console.log(Array.isArray(array) ) Commented Oct 2, 2016 at 15:01
  • 1
    typeof [] always returns object, all arrays are objects as well and typeof is not designed to distinguish different types of objects. Commented Oct 2, 2016 at 15:10

1 Answer 1

1

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)

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.