0

I found this question but unfortunately it was just closed. There are many good answers but I wonder why no one suggested the following solution:

a = a.concat(b)

The author said he don't wanted to have an new array but extend the array a.

Community
  • 1
  • 1
Johanna
  • 111
  • 7
  • 3
    `concat()` returns a **new** array. That is not the same as extending an array. Sometimes code depends on references not changing – Ian Sep 24 '14 at 14:19
  • yes but I set `a` on this array, so it will be updated to this array and so it is extended. I don't understand the problem :/ – Johanna Sep 24 '14 at 14:23
  • 2
    Like I said, `concat()` generates a **new** array, so nothing is extended. You may be setting `a` to the new array, but the original value (array reference) is lost – Ian Sep 24 '14 at 14:26
  • ok, but if i do this: `a.push.apply(a, b)`how can i access on the original reference of a? Where is the difference to setting a to a new array? – Johanna Sep 24 '14 at 14:30
  • I'm still new with Javascript and I try to understand it :) – Johanna Sep 24 '14 at 14:32

1 Answers1

1

Setting the local variable to the value does not necessarily mean that will propagate to everywhere that variable is referenced. Take the example:

var foo = (function() {
  var bar = [1, 2, 3, 4, 5];
  return {
    get: function() {
      return bar;
    },
    show: function() {
      $("html").append("<div>" + bar.length + "</div>");
    }
  };
})();

var a = foo.get();
foo.show();

a = foo.get();
a = a.concat([6, 7]);
foo.show();

a = foo.get();
a.push([6, 7]);
foo.show();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>

The second call to show prints "5", because bar was not modified by a = a.concat. Because a and bar are references, when you set a to the return value of bar.concat, a copy of bar is made and assigned to a. The location bar references does not change, nor do the contents of the array previously known as bar.

When one reference is reassigned, that does not propagate to every place referencing bar (if it did, copying would be nigh-impossible).


Getting into which array methods are the most helpful in this situation, you probably push or splice. It depends on the exact use (appending or inserting at a particular index, removing existing elements, one at a time or from another array).

Splice can do some interesting things within an array, and has the fun property of returning elements that are removed. It can both insert and replace elements, depending on the parameters provided.

Push does just that, appending elements to the end of the array as if it were a list. If you have another array, it.push.apply(other) is a handy way to combine them.

If you have access to Underscore.js, many of the collection methods in there can be useful. They typically return a new array, but offer such functionality as flatten and union.

ssube
  • 47,010
  • 7
  • 103
  • 140