Loop is adding too many items to the final array [duplicate] - javascript

This question already has answers here:
Array.fill(Array) creates copies by references not by value [duplicate]
(3 answers)
Closed 4 years ago.
When i use Array.fill to fill a multidimensional array, i get a weird behaviour when pushing to one of the arrays:
var arr = Array(2).fill([]);
arr[0].push(5);
console.log(arr);
//=> prints [[5], [5]]

fill is essentially doing this:
var content = [];
for (var i = 0; i < 2; i += 1) {
arr[i] = content;
}
So, your array will have a reference to the array you've passed to fill in each property.

It sounds weird, but what your code actually does is create an array ([]) and put a reference for that array in each of the items of the Array(2). So whenever you change that reference - every array that is referenced to that Array is changed.
It's exactly the same as:
var a = [];
var arr = Array(2).fill(a);
a.push(5);
console.log(arr[0][0], arr[1][0]);
a[0] = 2;
console.log(arr[0][0], arr[1][0]);
You can see that the values inside the arr are affected by the change to the a array.

Related

Why is prototype.push overwriting my previous data in an array [duplicate]

This question already has answers here:
Push is overwriting previous data in array
(2 answers)
Closed 5 days ago.
I have the following code. Essentially what I do is I have a loop, and within the loop I have logic that creates a few values. I want to insert those values into an Object, and then insert that Object into an Array.
Now in each iteration, the object values change, so in case this loop runs 2 times, I'd expect to have two different objects.
Problem is, on first iteration, I push a distinctive object into an array, and then on the 2nd iteration, I have a new object with different values, but after I do .push - it overwrites my earlier entry with the new values, and insert a new object into the array.
I.E. I end up have 2 identical objects in the array. What is happening?
var arr = [];
var filObj={};
for (var i = 0; i<3; i++){ //looping
//I do some logic and derive a few fields and insert them into my `filObj`
filObj['col1'] = 'Hello';
filObj['col2'] = 'Yellow';
filObj['col3'] = 'Seven';
arr.push(filObj);
}
You are inserting the same object in each iteration.
The fix is to a create a new object every time.
var arr = [];
for (var i = 0; i<3; i++){ //looping
var filObj={};
//I do some logic and derive a few fields and insert them into my `filObj`
filObj['col1'] = 'Hello';
filObj['col2'] = 'Yellow';
filObj['col3'] = 'Seven';
arr.push(filObj);
}

How to merge and add inner array of numbers in javascript? [duplicate]

This question already has answers here:
How to sum elements at the same index in array of arrays into a single array?
(7 answers)
Closed 3 years ago.
I am working with a multi-dimensional array.
the following is my array:
let arr = [[1,2,3],[1,2,3],[1,2,3]];
the length of the inner arrays will always be the same.
I want create a function to add all the arrays elements together with their respective elements and create a new array with the result.
so my desired output is
result =[3,6,9];
You can use nested for loop for that.
let arr = [[1,2,3],[1,2,3],[1,2,3]];
let res = Array(arr[0].length).fill(0);
for(let i = 0;i<arr[0].length;i++){
for(let j = 0;j<arr.length;j++){
res[i] += arr[j][i]
}
}
console.log(res)

Why is array = Array(10).fill(Array(20).fill(-1)) not the same as array [[-1,..,-1], ..., [-1,..,-1]]? [duplicate]

This question already has answers here:
Array.fill(Array) creates copies by references not by value [duplicate]
(3 answers)
Closed 4 years ago.
I tried to create a 2-dimensional array in javascript. (Actually, the code is written in typescript and will be used to style DOM Elements with Angular2 but, as far as I am concerned, it shouldn't have any effect on the result in this case.)
First way:
arrayi = Array(10).fill(Array(20).fill(-1))
Second way:
array = [];
for(var i: number = 0; i < 10; i++) {
array[i] = [];
for(var j: number = 0; j< 20; j++) {
array[i][j] = -1;
}
}
If I call array[1][2] = 2; it does what I expected, what means setting one element in the 2-dimensional array to 2.
However, if I call arrayi[1][2] = 2; every element arrayi[x][2] will be set to 2. (With x element {0,1,2,...,9})
Why is that? I don't understand it. So it would be nice if someone could explain it to me.
The arrays are defined as array: number[][] and arrayi: number[][] in typescript.
arrayi = Array(10).fill(Array(20).fill(-1)) fills with the same array.
You can even rewrite it like this
const arr1 = Array(20).fill(-1)
const arrayi = Array(10).fill(arr1)
console.log(arrayi.every(item => item === arr1)) //true
The reason is that you create one instance of array with 20 elements and put this single instance into each element of root array

Javascript is this feature built into JS? [duplicate]

This question already has answers here:
"Variable" variables in JavaScript
(9 answers)
Modifying a copy of a JavaScript object is causing the original object to change
(13 answers)
Closed 25 days ago.
In the code below you see that it recognises arrayi as array - i.
Is this system built into js? I was experementing and it didn't function when I wrote array(i) instead of arrayi. The question then extends beyond all to ask if you could do iarray, ariray, arrayii or array(i*i) (just want to figure out the syntax of how this works).
var array = []
var arrayAmount = prompt("Select number of array")
for (var i = 0; i < arrayAmount; i++) {
var arrayi = array
arrayi.push([prompt("Select name for array " + (i + 1)), ["sub-element 1", "sub-elemet 2"], ])
console.log(arrayi)
}
console.log(array1)
Edit: I checked if the code would work if the for loop declares its own arrays instead of copying another array. Turns out it did not work and declared arrayi as arrayi instead of array1 or array2
You're confusing several JS concepts. I'll make some assumptions to explain some things, but feel free to correct me and I'll adjust my answer.
I believe you meant to assign a value at a particular index in the array, but what you ended up doing is creating a variable arrayi that is a reference to array:
var array = [];
array[1] = "foo";
console.log(array); // [undefined, "foo"]
What you did instead was create a reference, which means two different variable names will evaluate to the same object/array:
var array = [];
var reference_to_array = array;
reference_to_array.push("foo");
console.log(array); // ["foo"]
console.log(reference_to_array); // ["foo"]
Your original question includes: "and it didn't function when I wrote array(i) instead of arrayi".
To which the answer is: array(i) should be changed to array[i] when working with arrays.
Instead of fixing your original issue, you ended up creating new variables.
To fix your original code:
var array = [];
// Added parsing to an integer
var arrayAmount = parseInt(prompt("How many items do you want to add to the array?"));
for (var i = 0; i < arrayAmount; i++) {
// Method 1: directly access the index
//array[i] = [ prompt("Select name for array " + (i + 1)), ["sub-element 1", "sub-element 2"] ];
// Method 2 (Recommended): push a new element onto the end of the array
array.push([ prompt("Select name for array " + (i + 1)), ["sub-element 1", "sub-element 2"] ]);
// Log this element
console.log(array[i]);
}

Strange behavior when add element to array by key [duplicate]

This question already has answers here:
Javascript array length incorrect on array of objects
(3 answers)
Closed 8 years ago.
I don't understand why is array so strange when I add element by key.
For example:
var test = new Array();
test['a'] = 'aaa';
test['b'] = 'bbb';
test.length == 0; // true. Why?
And when I run:
test.map(function(el){
console.log(el);
});
// nothing print. Why?
When I add element with push method everything works OK. Thanks
Arrays in javascript are not associative, you can't set keys like that i.e.
var test = [];
test.push('aaa');
test.push('bbb');
// OR
test[0] = 'aaa';
test[1] = 'bbb';
test.length = 2

Categories