Javascript - Modify an array duplicate without modifying the original array [duplicate] - javascript

This question already has answers here:
Why does changing an Array in JavaScript affect copies of the array?
(12 answers)
Closed 8 years ago.
I'm sure this is a stupid thing, but i can't solve it.
If i do this:
var arr = [1, 2, 3, "up"];
var duplicate = arr;
duplicate[3] = "down";
console.log(arr[3]); //"down"
console.log(duplicate[3]); //"down"
So why the original array got modified too? It is related to the fact that they point to the same array?
How to modify only the duplicate?

You need to clone your duplicate array... you can use the slice() method to do it:
var arr = [1, 2, 3, "up"];
var duplicate = arr.slice(0);
duplicate[3] = "down";
console.log(arr[3]); //"up"
console.log(duplicate[3]); //"down"

The original array was modified because using var duplicate = arr just means the value of duplicate is now equal to the value of arr. Changing either one will change the value of the array.
As for copying the array and its contents, this post has a full write up How do I correctly clone a JavaScript object?

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

How to check an array is subset of another array of arrays in js? [duplicate]

This question already has answers here:
Check whether an array exists in an array of arrays?
(11 answers)
Closed 3 years ago.
I have 2 arrays, where arr1 is a subset of arr2, but I am unable to check this using Javascript.
arr1 = [1,2]; //array1
arr2 = [[1,2],[2,3],[1,3],[1,4]]; //array2
I tried achieving this by using arr2.includes(arr1) which always returns false.
let arr1 = [1,2];
let arr2 = [[1,2],[2,3],[1,3],[1,4]];
console.log(arr2.includes(arr1)); //getting false
I expect the output to be true, but the actual output is false.
Can anyone help me solve this problem and direct me whether this is the right approach to solve this problem or not?
Use JSON.stringify and compare with the individual arrays in arr2
var arr1 = [1,2];
var arr2 = [[1,2],[2,3],[1,3],[1,4]];
arr2.forEach(function(e){
JSON.stringify(e)==JSON.stringify(arr1)?console.log(true):false})

Reverse Array in TypeScript is too fast [duplicate]

This question already has answers here:
Weird behavior with objects & console.log [duplicate]
(2 answers)
Reverse array in Javascript without mutating original array
(15 answers)
Closed 3 years ago.
I have a little problem with TypeScript. I want to reverse an Array. But before I reverse my Array, I want to write in into a local Storage.
The problem is, that I call the method to store the data before I call the method to reverse my array. But the stored data are already reversed.
Here is an example code and here is the Playground:
class TSRunner {
defaultArray = []
reversedArray = [];
fillArray() {
this.defaultArray = [1, 2, 3, 4, 5];
this.reversedArray = this.defaultArray;
console.log(this.reversedArray);
this.reversedArray.reverse();
}
}
let runner = new TSRunner();
runner.fillArray();
The output is already 5,4,3,2,1. But I want to get the 1,2,3,4,5 and after that, I want to reverse it. Maybe you could explain me this behaviour. I think it has something todo with the call by reference stuff.
Thanks before ;)

This array reassignment does not make sense to me [duplicate]

This question already has answers here:
Copy array by value
(39 answers)
Is JavaScript a pass-by-reference or pass-by-value language?
(33 answers)
Closed 4 years ago.
So Im trying to solve this algorithm where I have to sum 4 numbers from given array(first parameter) in order to get second passed parameter, and Im doing it in a pretty stupid way (question not about solving the algorithm).
Question is: why I can't delete values from array and recreate/reassign itself again, hope that make sence. Is it just how Javascript works or I did something wrong?
Thanks in advance!
function foo(arr1, sum){
let arr = arr1;
for(let i=0; i<9999;i++){
let val1=arr[Math.floor(Math.random()*arr.length)];
arr.splice(arr.indexOf(val1),1);
console.log(arr1);
let val2=arr[Math.floor(Math.random()*arr.length)];
arr.splice(arr.indexOf(val2),1);
let val3=arr[Math.floor(Math.random()*arr.length)];
arr.splice(arr.indexOf(val3),1);
let val4=arr[Math.floor(Math.random()*arr.length)];
arr.splice(arr.indexOf(val4),1);
if(val1+val2+val3+val4 == sum){
console.log(val1,val2,val3,val4);
return [val1,val2,val3,val4];
}
arr=arr1;
}
}
console.log(foo([2, 7, 4, 0, 9, 5, 1, 3], 20));
Actually arr1 is not the array itself but a Reference to it. If you do arr = arr1 you copy that Reference, and that Reference points to the same array as arr1. Therefore if you change the array arr is referencing, you also change the array arr1 is referencing. To copy an array:
arr = arr1.slice();

I have my array as arr=[1,2,3,4]. I pushed an element in it arr.push(5). Now I need to display my array as [5,4,3,2,1]. Any Idea? [duplicate]

This question already has answers here:
How can I reverse an array in JavaScript without using libraries?
(36 answers)
Closed 7 years ago.
I have an array as:
var arr = [1,2,3,4]
//Push and element to array
arr.push(5)
//Now, arr = [1,2,3,4,5]
I need to display my array as
Elements in array arr is:
5,1,2,3,4
Arr.reverse() gives me
5,4,3,2,1.
But i need
5,1,2,3,4
Simply use Array.prototype.reverse():
console.log(arr.reverse());
References:
Array.prototype.reverse().
This is the code you need to use :
arr.reverse();
Here is the w3school : http://www.w3schools.com/jsref/jsref_reverse.asp

Categories