copying of two arrays and console output - javascript

How come console shows "potato" instead of "JAN" when you console out arr2?
arr1[0]='Potato' is done after the line 4, so why arr2 is not equal to initial arr1? (array at line 1)

Both variables have an instance of the same array.
If you want to avoid that, make something like this instead const arr2 = [...arr1]. That will create new array with same elements as the first one.

You have to make new array from variable 1
Just try:
let arr2 = Array.from(arr1)

You can use const arr2 = [...arr1]; to immutable array clone
var arr1 = ['JAN', 'FEB'];
const arr2 = [...arr1];
arr1[0] = 'Potato';
console.log(arr2)
`

Related

Javascript - push String to Array returns Integer

I add some strings in an array.
console.log(arr1); // ['product_1']
let arr2 = arr1.push(name);
console.log(arr2); // 2
Why I receive number 2 in the second log when name is a String too?
I tried also let arr2 = arr1.slice().push(name); without success.
arr.push() modifies the arr itself and returns the length of the resulting array, to do what you want to do, you can do one of the two following methods
const name = "test";
arr1 = ['product_1'];
// Method 1
let arr2 = [...arr1, name]
console.log(arr2);
// Method 2
arr1.push(name);
console.log(arr1);
The number 2 in this case is the length of your array.
Documentation on MDN

Compare 2 Arrays and if one cell is empty add value to another

I have 2 Arrays:
arr1 = [[Name1,date, 10],[Name2,date, 20],[Name3,date,10]]
arr2 = [[Name1, " "], [Name2, randomtext]]
The names in Arr2 are less then in Arr1 and not in order.
I want to add 10 to the current value of arr1 if in arr2 the second cell is empty and obviously I want to add it to the correct Name.
I assume in both solutions that by 'empty' you actually mean ''. If this is not the case, then simply replace the latter with the first in both solutions.
Solution 1:
You can do that with two simple for loops:
const arr1 = [["Name1","date", 10],["Name2","date", 20],["Name3","date",10]]
const arr2 = [["Name1", ''], ["Name2", "randomtext"]]
for(let i=0; i<arr1.length;i++){
for(let j=0; j<arr2.length;j++){
if(arr1[i][0]==arr2[j][0] && arr2[j][1]==''){
arr1[i][2] +=10;
}
}
}
console.log(arr1)
Solution 2:
A shorter and more modern approach would be to use map:
const arr1 = [["Name1","date", 10],["Name2","date", 20],["Name3","date",10]]
const arr2 = [["Name1", ''], ["Name2", "randomtext"]]
arr1.map((r1,i)=>arr2.map(r2=>{if(r1[0]==r2[0] && r2[1]=='') arr1[i][2] +=10}))
console.log(arr1)
For the second solution make sure you have the v8 environment enabled.

How to copy json array and not change the original array value [duplicate]

This question already has answers here:
Cloning an object and changing values mutates the original object as well
(5 answers)
Closed 5 years ago.
How can I copy the array without changing the original array value?
var arr1 = [];
var arr2 = [];
arr1 = [{price: 10},{price: 20}];
console.log(arr1);
arr2[0] = arr1[0];
arr2[0].price += 5;
console.log(arr2);
//output arr1 = [{price: 15},{price: 20}]; Why???
//output arr2 = [{price: 15}];
deep copy the array using JSON.parse(JSON.stringify(arr1))
var arr1 = [];
arr1 = [{
price: 10
}, {
price: 20
}];
var arr2 = JSON.parse(JSON.stringify(arr1))
arr2[0].price += 5;
console.log(arr2, arr1);
My friend, you are dealing with object pointers, essentially what your doing is giving arr1[0] an alias called arr2[0]. and when you change 1 you change both. One way to fix this is to declare:
arr2=arr1
arr2.length=1;
arr2[0].price+=5;
By not referencing the object directly, but just duplicating the array, we arnt allowing the object to make pointers in memory, and the arr2.length is to get rid of the second element.
You are changing the value of arr1[0] by doing below:
arr2[0].price+= 5; // eventually arr2[0] = arr1[0] and that's why it is getting updated due to object pointers
You are not creating a new variable with the content of arr1. You are only copying the arr1 pointer to a new variable called arr2. Thus, as the object pointed by arr1 and arr2 is the same, if you modify one you modify the other.
The solution would be to create a copy of the array, for example:
arr2 = arr1.copy()

Javascript push an array to a 2-dim array

So i have 2 single dim arrays
array1 = [1,2,3];
array2 = [4,5,6];
And an empty 2-dim array
setArray = [[],[]];
How am i going to push the contents of the arrays to setArray so that it looks like this... considering we don't know the length of the single dim arrays?
setArray = [
[1,2,3],
[4,5,6]
];
I'm working on a project and my problem looks like this. Thank you.
if you just want to push contents of the two arrays in setArray you can do something like this:
Each element of setArray will have a reference to one of the arrays.
var array1 = [1,2,3], array2 = [4,5,6];
var setArray = [];
setArray.push(array1);
setArray.push(array2);
console.log(setArray);
array1 = [1,2,3]; array2 = [4,5,6];
setArray = [array1,array2];
console.log(setArray)
You can do it this way too.

Unwanted double assignment on array function

function myFunction()
{
var Arr2
if(Arr1!=null)
{
Arr2=Arr1
console.log("Arr2 before for: "+Arr2)
console.log("Arr1 before for: "+Arr1)
}
for(var index=-1+Arr2.length;index>=0;index--)
{
if(Arr2[index]=="to_delete")
{
Arr2.splice(index,1)
}
}
console.log("Arr1 after for: "+Arr1)
console.log("Arr2 after for: "+Arr2)
}
I create Arr2 in a function, Arr2=Arr1, the problem is that Arr1 is also being spliced during for, and from these last two console.logs i am informed that these 2 arrays are the same. (I only want to change Arr2)
When you do Arr2 = Arr1, you're just copying the reference to that array, you're not making a copy of the array itself. So both Arr1 and Arr2 will now refer to the same array.
Try changing
Arr2=Arr1
to
Arr2 = Arr1.slice()
which should copy all of the elements in Arr1 to the new Arr2. Check out Array.prototype.slice for more info.
You could just use filter Array method like this :
var arr2 = arr1.filter(x => x!="to_delete");
You are creating a reference to Arr1, not a new object.
Think of it this way:
Think of it this way: when you initialise Arr1, you're allocating it to a piece of memory on the heap. This reference is then given an address.
The assignment var Arr2 = Arr1 equals the same as saying, Arr2 is the same as Arr1 by reference. Which means it points to the same memory address.
If you want to make a copy of an object, a.k.a. pass it by value, you should use one of the following methods.
var Arr2 = Arr1.slice(0);
Keep in mind however that if your array contains objects, these are cloned by reference with this method. Example:
var Arr1 = [{a: 1, b: 2, c:3}, {d: 4, e: 5, f: 6}]
var Arr2 = Arr1.slice(0)
Arr1[0].a = 2;
console.log(Arr2[0].a) // this will output 2
If you want to easily do a deep clone without having to write the code to pass the object references by value, you can use something like lodash or just:
var Arr2 = JSON.parse(JSON.stringify(Arr1));
Which also works.

Categories

Resources