Why overwrite element of 2D array in javascript [duplicate] - javascript

This question already has answers here:
Copy array by value
(39 answers)
Closed 6 years ago.
I have a 2D array "allcolor" in javascript. So that I initialize each row of it with a 1D array same below code.
var allcolor=[];
var color=["#f73214","#f5f714","#54f714","#141df7","#006400","#556B2F","#2F4F4F",
"#808080","#8FBC8F","#4B0082","#9400D3","#483D8B","#1E90FF","#00BFFF",
"#FFFF00","#ADFF2F","#9932CC","#FF69B4","#FF1493","#8B0000","#8B4513",
"#B22222","#CD5C5C","#E9967A","#FF8C00","#DAA520","#F0E68C","#FFFAF0",
"#000000"];
for(p=0;p<x.length;p++){
allcolor[p]=color;
}
When I change each element of each row of allcolor, overwrite other element of all row of allcolor. When I run this bellow code, I see that all [..][0] and all [..][4] are same value '#000000' and '#ffffff'.
console.log(allcolor);
allcolor[0][0]='#000000';
console.log(allcolor);
allcolor[0][4]='#ffffff';
console.log(allcolor);
How can I change value of one row?

So, this happens, because javascript variables only store references to memory places where objects belong (kind of like pointers in C++). When you put color in the allcolor array 4 times, then they'll refer to the same object, thus if you change the value of one row, you change every row's value.
To avoid this, do
allcolor[p]=color.slice();

Related

Alternative of push method in javascript [duplicate]

This question already has answers here:
How to replace item in array?
(29 answers)
Closed 1 year ago.
I have an array called current markers, and each time a function is called the marker is added to the array
var currentMarkers=[];
var mymarker= new mapboxgl.Marker(el)
.setLngLat(marker.geometry.coordinates
)
.addTo(map);
this.currentMarkers.push(mymarker); // pushing into the array
Is there any other method out there so that i can just update the values of the array instead of pushing new values into it? example
just my concept
this.currentMarkers[0].update(mymarker);
Thank you so much for your time !
If you want to update a specific element of an array in JavaScript, just reference that element and assign it.
Example:
this.currentMarkers[0] = mymarker;

why is [[],[],[]] different than new Array(3).fill([])? [duplicate]

This question already has an answer here:
If we create an array of objects using new Array(len).fil({}); and then add a key in any of the objects, it gets reflected in all the 3 objects
(1 answer)
Closed 4 years ago.
So my question is the same as in the title. I saw that someone initiated a similar thing here (If we create an array of objects using new Array(len).fil({}); and then add a key in any of the objects, it gets reflected in all the 3 objects) but while everyone accused the improper method of questioning nobody gave a clear answer.
Array(3).fill([]) creates 3 elements referencing the passed object.
The answer is clear in javascript documentation:
The fill() method fills all the elements of an array from a start
index to an end index with a static value
It seems to me like the only answer in the question you linked to is perfectly clear.
Array.fill "fills" the array with static values. That is to say, you are creating on single empty array and then referencing it in all three of the locations, hence it is the same array in each of the outer array's indices

How to remove an array element from local storage? [duplicate]

This question already has answers here:
Remove array item from localstorage
(4 answers)
Closed 4 years ago.
I have an array of contacts in local storrage, and I need to remove, for example, the first element. How better to do? Is this expression correct?
localStorage.removeItem("allContacts"[0]);
localStorage contains string values. If you stringifyed an array and put it into localStorage, then you'll need to parse the array, delete the element you want, and then set the localStorage property again:
const allContacts = JSON.parse(localStorage.allContacts);
allContacts.shift();
localStorage.allContacts = JSON.stringify(allContacts);

push value in map of arrays at a specific postition [duplicate]

This question already has answers here:
How can I create a two dimensional array in JavaScript?
(56 answers)
Closed 5 years ago.
I am creating a map of array using this:
var m = new Map(Array(40).fill(new Array()).entries());
Now, I want to push values in those array. But when I do this:
m.get(1).push(10)
The value 10 gets pushed into all the arrays instead of the one at 1st position.
You could take another pattern to build independent arrays.
var m = new Map(Array.from({ length: 40 }, _=> []).entries());
m.get(1).push(10);
console.log([...m]);
fill gets single array an uses it to fill all rows of the given array, it doesn't create a new array for each row. This means that your single array reference is shared between all rows. Because array is a reference type, you use the single reference to manipulate it, so the actual object is changed. You can check this by comparing the references of each row.
const arr = new Array(2).fill(new Array());
console.log(arr[0] === arr[1]);
For creating separate arrays, you can see #Nina's answer above

jQuery (or JS) How to make a Randomized New Array From an existing one [duplicate]

This question already has answers here:
Sampling a random subset from an array
(15 answers)
Closed 8 years ago.
Say I had
var imgs = ["pItem1","pItem2","pItem3","pItem4","pItem5"]
How can get a new array from the current one, that randomly picks lets say 3 items from the old array and puts it in a new array.
var newArray =["pItem1," "pItem4," "pItem2"];
You're basically looking to take a randomly sampled subset of an array. One approach is to randomly shuffle the array, then take a slice from the beginning of the array. See this implementation of getRandomSubarray() in another answer: https://stackoverflow.com/a/11935263/2943575

Categories

Resources