1
$ node
> A = [0, 1, 23]
[ 0, 1, 23 ]
> B = A
[ 0, 1, 23 ]
> A.splice(0, 3)
[ 0, 1, 23 ]
> B
[]
> A
[]
> A = A.concat([1, 2])
[ 1, 2 ]
> B
[]

This is correct. But, is it possible that after calling concat, B array be equal with A?

I know that there is the loop solution, but what other alternatives are there to add multiple elements in multiple arrays that are equal?

BTW, I don't want to modify B directly (A = B = A.concat(...)).

Ionică Bizău
  • 109,027
  • 88
  • 289
  • 474
  • 2
    Why do you even need such a thing? – thefourtheye May 25 '14 at 08:56
  • @thefourtheye `1.js` exports an object that contains an array that is used in the module. `2.js` wants to modify that array so `1.js` will use `2.js` data. This is my case. – Ionică Bizău May 25 '14 at 08:58
  • if `A` and `B` refer to the same array, then `A.push(element)` will also show up in `B`. – Paul May 25 '14 at 08:58
  • @Paul Exactly. But I want to insert multiple elements. `A = A.contact(...)` doesn't work because the reference will be changed. `A.push(...);A.push(...);A.push(...)...` will change `B` as well, but the code will not be the best I guess. – Ionică Bizău May 25 '14 at 09:00
  • @ionica see Benjamin's answer. For adding multiple eleemnts, [Function.apply](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/apply) is a good helper to use with [Array.push](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/push) – Paul May 25 '14 at 09:04
  • @Paul You're right! I knew that there should be a shorter solution. :-) – Ionică Bizău May 25 '14 at 09:06

2 Answers2

4

Paul is correct, you could do:

A.push.apply(A,[1, 2]);

For those of you not aware, Array#push accept variable arguments, and Function#apply converts a variable arguments accepting function to an array accepting function.

Benjamin Gruenbaum
  • 270,886
  • 87
  • 504
  • 504
  • 1
    Oh, what a good idea! – Ionică Bizău May 25 '14 at 09:01
  • It's also considerably faster than the alternatives, with the exception being an inline for loop - which is why you see this trick often used with the `arguments` object over .slice or .splice in performance sensitive code (again, an inline for loop is even faster) – Benjamin Gruenbaum May 25 '14 at 09:04
2

You can use Array.prototype.splice itself, like this

var A = [0, 1, 23], B = A;
A.splice.apply(A, [A.length, 0].concat([1, 2]));
console.log(A, B, A === B);
// [ 0, 1, 23, 1, 2 ] [ 0, 1, 23, 1, 2 ] true

Here, A.length and 0 represent the starting position at the array and number of elements to remove respectively.

We concatenate that with the actual array of elements to be inserted. So, the arguments being passed to A.splice would look like this

A.splice(A.length, 0, 1, 2);

As splice does in-place operation, A and B still refer the same object.

thefourtheye
  • 233,700
  • 52
  • 457
  • 497