JavaScript Copy Array By Value - javascript

I have created an array and received another from a php file.
The data is fine but when i try to copy one array to another, it seems like when i change arr1 then arr2 is also changed.
It is being copied "by reference" and not "by value" as i need
I also tried slice() butit doesn't work, The variable does not being copied at all, not even "by reference" in that way.
// arr1[0] = "Hey";//this array is coming from another file and the data is fine
var arr2 = [];
arr2[0] = arr1[0];
arr2[0] += "1"; // right now arr1 and arr2 both has "Hey1" in them.
Any ideas?
Thank You

An array is an object in Javascript. As you might know objects are copied by reference. You could take a look here: What is the most efficient way to deep clone an object in JavaScript?

You can do a deep, rather than a shallow, copy of an array of strings like this:
var arr2 = [], i = 0;
for (i = 0; i < arr1.length; i++) {
arr2[i] = String(arr1[i]);
}
EDITED: oops, swapped deep and shallow.

Related

updating a JSON objects value with a for loop in Java Script

I have an array of 11 objects which contain JSON data. I wrote a function in which a new key with a zero value is added to each of the objects. Now I want to update the value of the said key in all 11 objects. The data is stored in an array2 with 11 numbers. My for loop doesn't seem to work for this, and the only way to do it (so far) is to hard code it. Does anyone has a suggestion how this can be done?
The desired outcome would be this:
array[0].new_key = array2[0];
array[1].new_key = array2[1];
The first art of the function, before the for loop with j, is for adding the new key into the original array and that part works.
for (i = 0; i < array.length; i++) {
array.map(i => i.new_key = 0);
console.log(array)
for (j = 0; j < array2.length; j++) {
array[i].new_key = array2[j];
console.log(array)
}
}
}```
I split it into two functions, I realized that I made it too complicated and it didn't made sense. I wrote a second function that only updates all the key values, so indeed, I removed the inner loop as it was not needed. Thank you for the help.
.map() does not modify the original array:
The map() method creates a new array with the results of calling a
provided function on every element in the calling array.
You will want to get the result of the map by assigning it to a variable, and see what is happening there. Right now you don't do anything with it, so it will just disappear.
While the above is true for maps, in this case the original array is being modified as we access the object's properties and modify them there.

Javascript array in array - first index is always overwritten

I have a problem with my JS function. For simplification, I want to fill an array (arr1) with n other arrays (arr2). In my loop I use a counter for the current postion in arr1 (cant use arr1.push for a reason). If I log all my arr2's in arr1 they are all the same, always the last one that was added. So I wrote a basic script to test it. I always log the first element and incement the counter.
I'm new to JS, is there some huge misunderstanding I don't get?
function test(){
var arr1 = [];
var arr2 = [];
var counter=1;
arr2[0]="first";
arr2[1]="first";
arr2[2]="first";
arr1[0]=arr2;
arr1[0].forEach(function(elem){console.log(elem);});
for (var i = 0; i < 10 ; i++) {
arr2[0]=counter;
arr2[1]=counter;
arr2[2]=counter;
arr1[counter]=arr2;
arr1[0].forEach(function(elem){console.log(elem);});
counter++;
}
}
<button onclick="test()">Click</button>
You can try to use the spread operator.
arr1[0]=[...arr2];
arr1[counter]=[...arr2];
An array is a reference type, so you always refer to the base, you don't put a copy of it inside of arr1 but a reference to the arr2.
You want a copy of arr2 to be assigned to arr1.
You can do this by creating a new Array, or more modern the ... spread operator
As Pointy said it, it just referenced the arr2 and doesn't create a copy.
So you need to
arr2=new Array();
at the beginning of the loop.

Circumvent References when deleting Array Content in JavaScript

I'm implementing a simple logging mechanism by storing arrays as log entries in a single array.
The code works like this:
var myarr = new Array();
var secondarr = new Array(4,5,6);
myarr.push(secondarr);
secondarr.length=0;
secondarr.push(5,5,5);
myarr.push(secondarr);
secondarr.length=0;
//check
for(var i = 0; i < myarr.length; i++){
var str="";
for(var j = 0; j < myarr[i].length; j++)
str+=myarr[i][j]+" ";
console.log(str);
}
I'm creating my single array myarr, in which logentries are stored. The secondarr stores data to log. Because I don't want to create a new array each time I log something into myarr, I wanted to set back the secondarr through secondarr.length=0.
However this deletes everything out of myarr as well, because of references!
Is there a way to circumvent creating new arrays for each log? The method of course works if I push secondarr.slice(), but this results in multiple arrays, which I'm trying to avoid.
replace each secondarr.length=0; by secondarr=[];. The first instruction modifies the length property of the array referenced by secondarr. The second one makes that secondarr now refers to a new empty array.
In any case, you have to create a new array for each logentry you want to store.

Copy substring of string array into new array in Javascript

I am looking to copy the substring of a string array into a new array without creating references. This is giving me a headache yet this should be fairly simple.
I tried NewArray[n] = OldArray[n].substr(x,y).slice(0) inside a loop and does not work. (I need to do a NewArray.sort() afterwards).
For the sake of example, say I got an OldArray with 2 elements:
['River', 'Lake']
I want the new array to be made of the first 2 characters (substring) of the old one such that:
['Ri', 'La']
copy the substring of a string array into a new array without creating references
Strings are primitive values in JavaScript, not Objects. There will be no reference when assigning the values of the old into the new array, especially when creating new strings with substr. The slice(0) you've used is superfluous when used with strings, and not necessary on arrays in your case, too.
Your code should work:
var oldArray = ["River", "Lake"];
var newArray = [];
for (var i=0; i<oldArray.length; i++)
newArray[i] = oldArray[i].substr(0,2);
// newArray: ["Ri", "La"]
This worked for me. Thanks #Bergi
const newArray = oldArray.map( str => str.substr(0,2) );

Javascript object array comparison

I have two array of objects in javascripts. Like arr1[] = {emp1,emp2,emp3} where inturn emp1 has emp1.name and emp1.address as property.
Something like
arr1={object {name='a',address='b'} {name='c',address='d'} {name='e',address='f'} }.
arr2={object {name='a',address='b'}}.
I wanted to compare name property of two array objects and populate the missing items into another array. So result will be result[]={'c','e'}
Whats is the efficient way in achieving this? I don't expect code, please guide me in the right direction. Thanks.
The Array.filter method might be helpful. Check out more on it here.
the function could look like
function foo(arr1,arr2){
var arr3 = new Array();
var x=0;
for (var j =0; j<arr1.length; j++)
for(var i=0; i<arr2.length; i++)
if(arr1[j].name != arr2[i].name){
arr3[x]=arr1[i];
x++;
}
return(arr3);
}
This will loop through the 2 arrays and if the elements are not the same then they will be put in the third array. this is checking if any name in aarr1 is the same as in arr2. it doesn't check the other way.(ie if arr2 has an element that does not exist in arr1 it will not be put in arr3) but at least it should get you started.the function will accept the 2 arrays and return the third.

Categories

Resources