0

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.

1
  • There is no real guarantee that an object/array will retain its address Commented Oct 8, 2019 at 17:53

4 Answers 4

4

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

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

a.push(...b);
Sign up to request clarification or add additional context in comments.

3 Comments

why not just a = [...b]?
also Object.assign(a, b)
@MedetTleukabiluly that will create a new array. I think OP wants to change a it in-place, although I'm not sure.
2

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);

2 Comments

what's the point in comparing var firstA = a;, a === firstA ? it's always a reference
@MedetTleukabiluly to show that a hasn't been reassigned. Superfluous, I know but it doesn't hurt.
1
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; });

2 Comments

why not just a = b.slice()?
@MedetTleukabiluly because I'm eating a very good sandwich and it's making me disoriented :)
0

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

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.