how to copy contents of one array into another. Javascript - javascript

i have a main array as
arrayVariable = [1,2,3];
and i want another to variables to have the same content as above. If i do
anotherVariable = arrayVariable;
It will just reference that array and they wont be independent of each other.
I tried this solution, but it didnt work.
var anotherVariable = arrayVariable.slice();
Edit:
Another question,
while passing array through a function, does it pass the array or is it passed by reference?
like
var array = [];
someFunction(array);
function someFunction(array){};

Check the below code, look they are independent.
arrayVariable = [1,2,3];
var anotherVariable = arrayVariable.slice(); // or .concat()
arrayVariable[0] = 50; // Hopefully it should not change the value of anotherVariable
alert(anotherVariable); // Look value of anotherVariable is not changed

you can try
var aa = [1,2,3,4,5,6];
var bb = [].concat(aa);//copy aa array to bb, they are now independent of each other.
hope helps.

You can do it using a loop.
arrayvariable=[1,2,3];
for (var i=0;i<arrayvariable l.length;i++)
//while could also be used.
{
anothervariable[i]=arrayvariable[i];
}

Related

Modifying an object causes the modifications to be reflected in a copy of that object previously pushed to an array

I have code similar to the following
var l_mattes_array = [];
var matte_array = [];
var mattes = [];
mattes[0] = "<test><imgsrc>test1</imgsrc></test>";
mattes[1] = "<test><imgsrc>test2</imgsrc></test>";
$(mattes).each(function(i, el)
{
matte_array.imgsrc = ($(el).find("imgsrc").first().text());
l_mattes_array[i] = matte_array;
console.log(l_mattes_array[i]);
});
console.log(l_mattes_array);
The output I am getting is:
[imgsrc: "test1"]
[imgsrc: "test2"]
(2) [Array(0), Array(0)]
0:[imgsrc: "test2"]
1:[imgsrc: "test2"]
The output I want:
[imgsrc: "test1"]
[imgsrc: "test2"]
(2) [Array(0), Array(0)]
0:[imgsrc: "test1"]
1:[imgsrc: "test2"]
The problem is that matte_array is a reference type (all objects are, and arrays are objects, so yes). What this means is, when you say l_matte_array[i] = matte_array, you are actually setting that index of l_matte_array to a reference to the value of the array matte_array, and then when you modify the matte_array again in the second iteration, you are modifying the value referenced by matte_array, that value is the same value that you set l_matte_array[i] to refer to in the preceding iteration.
So all your l_matte_array indices are merely holding a reference to a single shared value, and you have modified that value to have its imgsrc property be equal to "test2".
Go read this MDN article, you will come out of it having a nice understanding of JavaScript datatypes.
Another problem with you code is, you are using an array as an object, which is inappropriate. Use an array if you want to take advantage of its functionality of having numerically indexed elements; if you want to group some properties and/or methods somewhere, just use a normal object (created with a literal: var obj = {}); if you want something to hold a single value, use a variable.
So, I solved your problem in the following way (I am not using a variable for imgsrc because I believe you are modifying the objects that hold imgsrc sometime later in your code, if you are not adding any properties/methods to the objects that you push to l_mattes_array, just replace my object with an imgsrc variable):
var l_mattes_array = [];
var mattes = [];
mattes[0] = "<test><imgsrc>test1</imgsrc></test>";
mattes[1] = "<test><imgsrc>test2</imgsrc></test>";
$(mattes).each(function(i, el) {
var matte_object = {};
matte_object.imgsrc = ($(el).find("imgsrc").first().text());
l_mattes_array[i] = matte_object;
});
console.log(l_mattes_array);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
The problem is you're referencing the same object (matte_array), so you're changing the src property but the reference is still the same. What you could to is just initialize matte_array inside the cycle, so each time it becomes a new array, like this:
// ...
// var matte_array = []; // Should not be here
// ...
$(mattes).each(function(i, el)
{
var matte_array = []; // Should be here
// ...
});
// ...
Here you have a working example: https://jsfiddle.net/6j73wgdw/
You can use Array.prototype.map() and remove all html tags with the regular expression /<{1}[^<>]{1,}>{1}/g.
Code:
const mattes = ['<test><imgsrc>test1</imgsrc></test>', '<test><imgsrc>test2</imgsrc></test>'];
const l_mattes_array = mattes.map(el => ({imgsrc: el.replace(/<{1}[^<>]{1,}>{1}/g, '')}));
console.log(l_mattes_array);
I added
matte_array = [];
after adding to l_mattes_array and that fixed it

Storing key values array in localstorage

I am trying to store array in localstorage with following code :
var tempval = [];
tempval['key'] = 1;
localStorage.setItem("Message", JSON.stringify(tempval));
but in localstorage it showing only []
So how to store it and where I am doing mistake ?
Here is your code:-
var tempval ={};
tempval.key = 1;
localStorage.setItem("Message", JSON.stringify(tempval));
So Your Question is not that much clear to me but i am trying to give you a general solution for storing multidimensional array in local storage ,
var a= [[1,2,3],["hello","world"]]; // multi dimentional array
console.log(a);
var b = JSON.stringify(a); // converting the array into a string
console.log(b);
localStorage.setItem("TestData",b); // storing the string in localstorage
var c= JSON.parse(localStorage.getItem("TestData")); //accessing the data from localstorgae.
console.log(c);
Here is the code running in Jsbin
JavaScript does not support arrays with named indexes.Arrays always use numbered indexes in javascript. Use object if you wanna use named index.
Using array (numbered index)
var tempval = [];
tempval[0] = 1;
Using object (named index)
var tempval = {};
tempval['key'] = 1;
Use var tempval ={}; instead of var tempval = [];
This question has been answer already (duplicate of):
https://stackoverflow.com/a/3357615/10387837
The short answer is localStorage.setItem only supports strings as arguments. In order to use it with arrays its recommended to use JSON.stringify() to pass the parameter and JSON.parse() to get the array.

Can't reference array by index

I have an array defined as:
var subjectCache = [];
I then have some code to build it up, which is working ok.
However, if I try to reference the array by an index, e.g.:
var x = subjectCache[0];
or
var x = subjectCache[1];
I get undefined.
Also subjectCache.length is always 0 (zero).
if I try to reference it by its key, e.g.:
var x = subjectCache['12345'];
it works.
Is this normal? Shouldn't I be able to reference it by its index whatever?
I'm using Internet Explorer, if it makes a difference (and it probably does :( )
[Edit]
this is the code I'm using to build the array, although I really don't think it is to blame.
It's a callback from a webservice call. This is working fine and the array is being populated.
var subjectCache = [];
var subjectCacheCount = 0;
function refreshSubjectsCallback(data) {
// update subjects
// loop through retrieved subjects and add to cache
for( i=0; i < data.length; i++ )
{
var subject = data[i];
var subjectid = subject.SubjectId;
subjectCache[subjectid] = subject;
subjectCacheCount += 1;
}
}
[/Edit]
You're probably assigning keys manually instead of using subjectCache.push() to add new elements to the array:
var array = [];
array['foo'] = 'bar';
console.log(array.length); // 0
The length attribute isn't going to reflect those changes the way you'd expect:
> var a = [];
undefined
> a[100] = 2; // The previous `100` entries evaluate to `undefined`
2
> a.length;
101
Instead, use an object:
var object = {};
object['foo'] = 'bar';
for (var key in object) {
var value = object[key];
console.log(value);
}
From your symptoms, it sounds like you are trying to treat the array as an associative array.
In Javascript, arrays work like this:
var a = [];
a[1] = 10;
alert(a.length);
Objects work like this:
var o = {};
o.myProp = true;
o["myOtherProp"] = false;
Arrays only work with numeric keys not strings. Strings assign properties to the object, and aren't counted as part of length nor it's numeric indices.
When building the array, make sure you are assigning to a numeric position within the array.
No, it will not work, because you haven't created arrays but objects.
you will have to access it by its key.
var x = subjectCache['12345'];
If this works and subjectCache.length doesn't, I think you are making an object not an array. You are confused.
Somewhere along the road you lost the array, and the variable subjectCache points to a different kind of object.
If it was an array, it can't have the length zero and contain an item that is reachable using subjectCache['12345']. When you access an item in an array it doesn't make any difference if you use a numeric index or a string representing a number.

JavaScript Variable Declaration

This is a really stupid question, but I'm just drawing a blank here...
What type of variable declaration is this:
var s1 = [1,2,3,4]
Also, How can I construct a variable like this from multiple objects when the amount of those objects is unknown. This is what I came up with, which doesn't work.
var s1 = [];
for(x in data[i].uh) {
s1 += data[i].uh[x];
}
var s1 = [1,2,3,4]
is an array declaration of four integers using "Array Literal Notation"
You don't need a loop to copy the array, simply do this:
var s1 = data.slice(0);
or in your example you might want this:
var s1 = data[i].uh.slice(0);
Read more about copying arrays here: http://my.opera.com/GreyWyvern/blog/show.dml/1725165
"The slice(0) method means, return a
slice of the array from element 0 to
the end. In other words, the entire
array. Voila, a copy of the array."
That is called an Array, which can be declared with new Array() or by using the array literal [] as in your example. You can use the Array.push() method (see docs) to add a new value to it:
var s1 = [];
for(x in data[i].uh) {
s1.push(data[i].uh[x]);
}
This
var s1 = [1,2,3,4]
is an array declaration.
To add an element to an array, use the push method:
var s1 = [];
for(x in data[i].uh) {
s1.push(data[i].uh[x]);
}
s1 is an array, it's a proper Javascript object with functions.
var s1 = [];
is the recommend way to create an array. As opposed to:
var s1 = new Array();
(see: http://www.hunlock.com/blogs/Mastering_Javascript_Arrays)
To add items to an array use s1.push(item) so your code would be:
var s1 = [];
for(x in data[i].uh) {
s1.push(data[i].uh[x]);
}
As a side note, I wouldn't recommend using for-in, at least not without checking hasOwnProperty.
It's declaring a local variable with an Array with 4 members.
If you want to append to an Array, use the push() method.
That is an array. To add to arrays you would use Array.push(). For example:
var s1 = [];
s1.push(1);
s1.push(2);

Populating another array from array - Javascript

Very simple thing I am trying to do in JS (assign the values of one array to another), but somehow the array bar's value doesn't seem affected at all.
The first thing I tried, of course, was simply bar = ar; -- didn't work, so I tried manually looping through... still doesn't work.
I don't grok the quirks of Javascript! Please help!!
var ar=["apple","banana","canaple"];
var bar;
for(i=0;i<ar.length;i++){
bar[i]=ar[i];
}
alert(ar[1]);
And, here is the fiddle: http://jsfiddle.net/vGycZ/
(The above is a simplification. The actual array is multidimensional.)
Your code isn't working because you are not initializing bar:
var bar = [];
You also forgot to declare your i variable, which can be problematic, for example if the code is inside a function, i will end up being a global variable (always use var :).
But, you can avoid the loop, simply by using the slice method to create a copy of your first array:
var arr = ["apple","banana","canaple"];
var bar = arr.slice();
copy-or-clone-javascript-array-object
var a = [ 'apple', 'orange', 'grape' ];
b = a.slice(0);
In ES6 you can use Array.from:
var ar = ["apple","banana","canaple"];
var bar = Array.from(ar);
alert(bar[1]); // alerts 'banana'
You have two problems:
First you need to initialize bar as an array:
var bar = [];
Then arr should be ar in here:
for(i=0;i<arr.length;i++){
Then you'll get alerted your banana :)
With ES6+ you can simply do this
const original = [1, 2, 3];
const newArray = [...original];
The documentation for spread syntax is here
To check, run this small code on dev console
const k = [1, 2];
const l = k
k === l
> true
const m = [...k]
m
> [1, 2]
k === m
> false
You have misspelled variable ar
Try this
for(i=0;i<ar.length;i++){
bar[i]=ar[i];
}
alert(ar[1]);
The problem probably here in the for loop statement:
for(i=0;i<ar.length;i++){
bar[i]=ar[i];
}
alert(ar[1]);
You need to fix to ar.length instead of arr.length. And it's better to initialize bar as: var bar = [].
In your code, the variable arr in the for loop is not the same as your original array ar: you have one too many r.

Categories

Resources