1

I am trying to chain multiple methods in Array.

Original array:

this.array = [1, 2, 3, 4, 5, 6];

Clone:

this.array.slice(0);

Change the first element

this.array.splice(0, 0, 10);

Running these individually works.

Combining both:

this.array.slice(0).splice(0, 0, 10);

This doesnot work. Why?

2
  • 1
    Combining works. But you don't store the result of slice invocation, so you can't see it. Commented Jul 30, 2015 at 10:10
  • @hindmost I see. Is there a way to have splice run on cloned instance without creating additional arrays? Commented Jul 30, 2015 at 10:17

2 Answers 2

2

Because this.array.splice(0, 0, 10); will return a new array(containing the removed elements - in this case an empty array since no element is removed) not the source array on which it was called on.

In your case you are using a clone of the original array, so you are loosing the reference to the cloned instance.

So this.array.slice(0) will return a clone on which the .splice(0, 0, 10) is performed(it will update the cloned object) but the splice operation will return a new array(with removed objects) not the cloned instance so we looses reference to it

So the solution is to use a temp reference like

var tmp = this.array.slice(0);
tmp.splice(0, 0, 10)
Sign up to request clarification or add additional context in comments.

1 Comment

array.slice is cloning the original array. Shouldn't splice execute on cloned array? How do you keep reference to cloned instance? By creating a temporary array?
0

It doesn't work because the second splice will operate on the return value of the first, and return value of array.splice() is a new array containing the elements that have been removed from the original array.

In short, array.splice() is not suitable for chaining in this way.

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.