Blaine Lafreniere
Blaine Lafreniere

Reputation: 3600

How do I load the values from one array, into another array, without changing the memory address of the array receiving the new values?

If I do this:

a = []
b = [1, 2, 3]
a = b

a will then refer to b

I want to copy all of the values in b into a without changing any memory address/references.

Upvotes: 0

Views: 43

Answers (4)

Narottam
Narottam

Reputation: 39

A= b.slice(). It will create a shadow copy of element without changing original one. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/slice

Upvotes: 0

Nina Scholz
Nina Scholz

Reputation: 386726

You could push the values without changing the reference from a or b.

var a = [],
    b = [1, 2, 3];

a.push(...b);

Upvotes: 4

VLAZ
VLAZ

Reputation: 29090

If you want to populate a in-place, without ever discarding the initial array, then you can simply loop over b and add all the items in a:

var a = []
var b = [1, 2, 3]

var firstA = a; //get a initial element


b.forEach(function(item) { 
  this.push(item)
}, a);// <-- pass `a` as the `this` context

console.log("`a` is unchanged", a === firstA);
console.log("`a` is not `b`", a !== b);
console.log(a);

Upvotes: 2

Pointy
Pointy

Reputation: 413866

let a = b.map(x => x);

The .map() function will create a new array with values generated from the source elements via the passed-in callback function.

As noted in a comment

let a = b.slice();

is pretty much exactly the same.

Basically this saves you the step of

let a = [];

since one brand-new empty array is as good as another. However, if you really have your heart set on using the empty array explicitly initialized, you could use

b.forEach(x, i) { a[i] = x; });

Upvotes: 1

Related Questions