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

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

Related

Why does putting a variable in angle brackets access the first value of an array [duplicate]

This question already has answers here:
Multiple assignment in JavaScript? What does `[ a, b, c ] = [ 1, 2, 3 ]` mean?
(4 answers)
Closed 1 year ago.
I've been using this trick a few time now but I still can't wrap my head around why this works and can't seem to find the answer. Could anybody please explain ?
let myArray = [0, 1]
let [myVar] = myArray
console.log(myVar) // outputs 0
How is [myVar] the same thing as putting [0] behind myrArray ?
Edit: already asked and answered here :
Multiple assignment in javascript? What does [a,b,c] = [1, 2, 3]; mean?
Thank you everyone
You are probably looking for this reference.
But basically, the brackets can be used to assign individual elements of a structure/array to variables, and it can be used with more than one, as well.
E.g.:
let myArray = [0, 1]
let [myVar1, myVar2] = myArray
console.log(myVar1) // outputs 0
console.log(myVar2) // outputs 1
PS: fyi these [] are square brackets, and these <> are angle brackets.
it is call "Destructuring_assignment"
you can read more on that here
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment

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

Javascript .push() variable reference/destruction [duplicate]

This question already has answers here:
Is JavaScript a pass-by-reference or pass-by-value language?
(33 answers)
Closed 5 years ago.
Ran in to this and I can't find documentation explaining the change- why does .push() change an array when it's applied to a new array that is set equal to that original array?
ex:
var arr = [1, 2, 3, 4, 5]
var newarr = arr
newarr.push(3)
console.log(newarr) //returns [1, 2, 3, 4, 5, 3] as expected
console.log(arr) //returns [1, 2, 3, 4, 5, 3] as well
What's happening here? I'm not applying any methods to arr (that I can see). It looks like arr and newarr are still linked in a way that doesn't apply to other variables, or .push() is invoking the newarr assignment line somehow?
For contrast, this is analogous to what I was expecting-
var x=6
var y=x
y=y*6
console.log(y) // now 36
console.log(x) // still six
The difference between your examples is arrays are mutable, and numbers aren't.
When you write var newarr = arr, you're literally saying that newarr is arr. You need to make a copy of the array to get the behavior you expect.
With the number example, since numbers are immutable, you're never changing the numbers themselves.
To do that you should use the splice method, this method will create a copy of your array, not changing the original.
Nevertheless you should know that when you do the attribution newarr = arr you're not creating a new independent variable that is an array, rather you're created another pointer to the same array.

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

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?

Categories