Javascript - array connect to another [duplicate] - javascript

This question already has answers here:
Copy array by value
(39 answers)
When I assign a variable to another variable does it not link them together?
(1 answer)
Closed 9 years ago.
I have really weird situation:
when I do that code:
var origin_array = [1,2,3];
var m = origin_array;
m.pop();
alert(origin_array);
origin_array value will be 1,2
eventhough I didn't changed it
but if I make that code:
var x = 5;
var y = x;
y--;
alert(x);
x still be 5, it won't be connected to "x" as you can see from the 1st example.
So my question is how do I make the "m" array unique, which not change the origin array?

You need to explicitly make a (shallow) copy or clone of origin_array:
var m = origin_array.slice(0);
This is not needed for primitive values, such as strings and numbers.
It's important to understand that although the above will prevent the issue you were experiencing, the same may happen again deeper down if you're dealing with more complex structures, and in some cases a "deep clone" is necessary.

Arrays are assigned by reference. That means that when you do this:
var origin_array = [1,2,3];
var m = origin_array;
m just points to the exact same array as origin_array. There is only one array and both origin_array and m point to it. If you modify it via either variable, they will both see the modification because you're modifying the one array that they both point to.
In javascript, both objects and arrays are assigned by reference like this. Assigning them does NOT make a copy. If you want an assignment to generate a copy, you have to explicitly make a copy. For an array, that is easy as you can just do:
var origin_array = [1,2,3];
var m = origin_array.slice(0); // makes a shallow copy
m.pop();
console.log(origin_array); // [1,2,3] because origin_array was not changed

Related

Why does it change the array(argument) value in a function, when I already passed the array(argument) values to another one to modify? [duplicate]

This question already has answers here:
Copy array by value
(39 answers)
Closed 3 years ago.
So I need the original(argument) array to stay the same, AND have another array (array2) with it's values to make some changes on it but mantain the original(argument) array intact.
Example:
let wtf = function(array){
let array2 = array
array2[0] = array2[0].replace(array2[0][0],"1")
console.log( array + " " + array2)
}
wtf(["a","b"])
Result in console:
1,b 1,b
BUT I need a,b 1,b
(that comes from: array = a,b and array2 = 1,b )
Thanks!
I think this is a reference value vs a clone value problem.
With your let array2 = array line, I think you're creating a reference to the same in-memory object, so you're actually modifying a single array twice, even though it looks like you've created another one.
To create a 'true' clone you can try something like:
let array2 = JSON.parse(JSON.stringify(array));

Assigning multiple indices at once from one list [duplicate]

This question already has answers here:
JavaScript Object Literals & Array Literals
(4 answers)
Closed 5 years ago.
I have five user variables with different names. I'd like them to end up in an array, and am wondering if I can do the assignment to multiple array indices in a single line. Currently, if I do this
var users = {user5k, user10k, user15k, user20k, user25k};
I can't index it later (says users[0] is undefined). So I want the indices built in to the assignment. Something along these lines:
var users = {};
users[0:4] = {user5k, user10k, user15k, user20k, user25k};
This doesn't seem possible in JavaScript, meaning I have to do this:
var users = {};
users[0] = user5k;
users[1] = user10;
// ... et cetera
Is there a way to accomplish the first solution?
When you use {} you're creating an object, not an array. Use [] for arrays.
var users = [user5k, user10k, user15k, user20k, user25k];
If you want to replace part of an array that already exists, you can use Array.prototype.splice()
var users = [];
users.splice(0, 4, [user5k, user10k, user15k, user20k, user25k]);

Assigning objects in Javascript: shallow or deep copy? [duplicate]

This question already has answers here:
JavaScript by reference vs. by value [duplicate]
(4 answers)
Closed 7 years ago.
I want to know if javascript does shallow or deep copy when copying objects.
const a = ['value1', 'value2'];
const b = ['value3', 'value4'];
const new_ab = [a, b];
new_ab are going to have new allocated values or a reference? If it is a deep copy, how can I make it to be swallow? Thanks.
As alluded in the comments, JavaScript operates entirely on references, the only exception being that primitive values are kept on the stack and a program does not therefore require a reference to access them. In your example all variable declarations create new values - each an instance of Array - however what is returned from declaring an array is a reference, not the array itself. For example, [1, 2] is an array of values (integers), but [a, b] is an array of references.
So... nothing is copied. We can demonstrate this by placing an object as an element of an array and inspecting that a previously assigned property is still accessible through the new 'parent' array.
(And to answer your question in the comments, yes, your example is more performant than if you (or JavaScript) were to copy values.)
'use strict';
const arrayOne = [];
arrayOne.someProperty = "This string is a property of `arrayOne`, " +
"accessed via the reference to it in `arrayTwo`."
const arrayTwo = [arrayOne];
span.innerHTML = arrayTwo[0].someProperty;
<span id="span"></span>

Moving element inside an object in javascript [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
JavaScript Array rotate()
I have a tricky question for you. I have an object who contain different values and I want to change the index of on element so My first element has to become the last or the third or whatever I want. Is that possible in javascript ??
var object = [{0},{1},{2}]
to
var object = [{2},{0},{1}]
This is an example of what I would like to do.
Thanks in advance.
Your from and to example is a little hard to understand the intent, but based on the body of your question asking
My first element has to become the last or the third or whatever I want
Writing a method to swap 2 elements in an array is easy enough:
function swapElements(a, x, y){
var temp = a[x];
a[x] = a[y];
a[y] = temp;
}
Live example: http://jsfiddle.net/pwY9L/
I assume you mean:
var array = [0,1,2];
It doesn’t really matter if the array contains numbers, objects or whatever. If you want to modify this array, there are many ways to do this in javascript andyou can read up about all the Array prototypes here: https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array
F.ex, move the last one and place it first:
array.unshift(array.pop());

copying an array of objects in javascript [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Copying array by value in javascript
How to copy an array of objects to another array in Javascript?
var qwerty1 = arr;
var qwerty2 = arr;
Both qwerty1 and qwerty2 may look different but point to the same reference.
I read somewhere that "assigning a boolean or string to a variable makes a copy of that value, while assigning an array or an object to a variable makes a reference to the value." So my two arrays post different operations return the same objects.
Any light in this regard?
The idiomatic way to copy an array in Javascript is to use concat:
var qwerty1 = arr.concat();
var qwerty2 = arr.concat();

Categories