JavaScript methods not working on copied array - javascript

I can't figure out what's going on here... I'm trying to copy an array, and then shuffle and join the copy, but it just isn't cooperating.
I have a JS file and am initializing a new array at the top:
var myArray = [];
On load of this JS file, I am pulling data from the Facebook API and stickin' the results in myArray with some HTML around it.
I then have a function which I call on button click which creates a new variable from myArray and then joins and prints out the text in a div element:
var namesList = myArray;
namesList.join('');
$('#my_div').text(namesList);
It's obviously been simplified, but the premise is the same.
My problem is, the array is not joining like it should. It remains in array form and nothing I've tried has fixed this. I've also tried:
var namesList = myArray.slice();
and
var namesList = myArray.slice(0);
to no avail.
HOWEVER: I can manipulate myArray with no problems in the same function and get the results I need. The problem with that is, I need to be able to shuffle the array each time the function is called and then print it out as text; this is why I am copying it in the first place.
For the life of me I can't figure out why this isn't working. All I need to do here is to create a copy of the variable within the scope of the function I'm calling, shuffle it, join it, and print it.
How do I fix this? OR, is there a better alternate? Many thanks in advance!

The join() method returns a string rather than modifying the array reference - you need to change your code to this:
var namesList = myArray;
namelist = namesList.join('');
$('#my_div').text(namesList);

That's because namesList still is an array. join() returns a string, which you should use:
var namesList = myArray.join('');
$('#my_div').text(namesList);

namesList.join('');
This joins the array then throws the result away. You want
namesList = namesList.join('');

Related

Add output to an array of each for loop

I'm trying to call a REST API using for loop and store the output to an array. But the output shows in different arrays for each and every rest API call instead of everything in one array
for each (name in car.cars){
for(i=0; i<count;i++){
var arr = [];
var newid = car.cars[i].name;
var url = "myhost"
var method = "GET"
var response = "output from REST call"
arr.push(response)
}
}
But the output shows in different arrays for each and every rest API call instead of everything in one array
Where is "the output" there's nothing in your code.
Your Problem is that you're declaring the var arr = []; inside your for loop.
Initialize the array before the loop starts and just add your responses to that array.
Instead your creating a new array for each iteration of for(i=0; i<count;i++)
Take a step back and look at your code again. Where are you declaring your array? Inside the loop.
Next, ask yourself; what is the scope of that array? Only within the loop. Even if just in the outer loop, it won't stick around because as soon as that loop finishes, the array disappears.
Create the array and use it from outside the loops (both of them).
Further reading: Declaring variables inside or outside of a loop
UPDATE 4/30/2019: Thanks to #AuxTaco, I crossed out my inaccurate description of scope in JS. Please see the links in his comment for more reading on this!

Appending a variable to an array without changing it

I'm currently working on a pre-bootcamp course and haven't been able to find help online in order to solve a problem that has me a bit confused.
I understand when we use JavaScript we have push(), pop(), shift() and unshift() methods we can use in order to add/remove from an array. The problem I'm running into is the test question ask:
1) Arrays appendKitten(name) appends a kitten to the kittens array and returns a new array,
leaving the kittens array unchanged:
I've been confused for nearly a day in solving this problem. I get when we do want to change the array we'll use one of the methods. For example when we append it'll be:
var kittens = ["Milo", "Otis", "Garfield"]
function destructivelyAppendKitten(name){
kittens.push(name)
return kittens
}
Which will push a new kitten(name) into the array. Now in order to solve the previous test I've written:
function appendKitten(name){
var newArray = []
var kittens = kittens.concat(newArray);
kittens.push(name)
return kittens
}
but continue to receive the same error. Is there something I'm missing?
My thought process in solving this question:
1- We are calling a function names appendKittens with a single argument -> name.
2- We are pushing data from the kitten variable into a local kitten instance in order to have the same array.
3- We push whatever name passes in the parameter into the new array.
4- Return the new array which had the push() performed leaving global kitten untouched.
Is my thinking process off? any ideas to where I'm off? All those who help. Thank you, really do appreciate it.
function appendKitten(name){
var newArray = kittens.slice();
// or ES6 way
// var newArray = [...kittens];
newArray.push(name)
return newArray
}

javascript pointers array or #define for abbreviation

I have a multi-dimensional array with different types of variables, like this:
array = [ [[file, name, visible], [ArrayPoint, ArrayOther], ...], [[file2,...], ..] ]
now in my code multiple times I have to call (for example) an Array() of points which is located in myArray [X] [1] [0].
I wanted to know if there was the possibility of creating definitions or pointers to the array position to shorten the code, because often I do not remember the variable positions.
// access the value at the address available in pointer
var *pointArray = &myArray[X][1][0];
// my code
*pointArray.push(pint_x, point_y);
============== VS ==============
myArray[X][1][0].push(pint_x, point_y);
thank you very much!! and good evening.
by Marco.
If you do
var pointArray = myArray[X][1][0];
It will make a copy of the reference to the array at myArray[X][1][0]. Therefore, any subsequent mutations to the elements of pointArray will also change the elements of myArray[X][1][0].
Note that reassigning a new value to pointArray as a whole would not effect myArray[X][1][0], since that would only make pointArray store something else.
Assignments do not copy/clone objects in JavaScript, they only make the variable on the left-hand side reference the same object as what's on the right-hand side.
var outer = [[0,1,2],[3,4,5]];
var inner = outer[1];
inner.push(6);
console.log(JSON.stringify(outer));
inner = [];
console.log(JSON.stringify(outer));
ok, thanks I understand.
my problem was that I created the variable called before filling the main array.
this is because I create the empty array structure, but is filled successively by the program events.
now to solve the problem I create the connection variable after the first event push to the primary array.
thank you very much for your availability.

javascript array attributes passed by reference

in this example, it seems that we can use a variable (here "second") to fill the array myArray, as if second was a "reference" to myArray : is that really what happens here?
var myArray = [];
var second = myArray;
second.target = … //we fill the "second" variable
second.offsetX = …
second.offsetY = …
var target = myArray.target; //then we retrieve the result from myArray
if (target) {
Thanks
second was a "reference" to myArray : is that really what happens here?
Yes.
Objects—like arrays—in JavaScript are passed and assigned by reference.
From your example, myArray and second both point to the same object in memory.
Yes, this is exactly what happens here. When you (for example) push new elements to second, you can read them later from myArray.
BTW, I sense that you're doing something strange. Why do you set an offsetX on an array?
This is called a shallow copy. You have a reference (var second = ...) to the original array (var myArray = ...), they both are pointing to the same memory in the memory of the JavaScript virtual machine.
This way you can access the array either by second or myArray.
var myArray = [];
This is just an array declaration It is same as var myArray=new Array();
About Array Referencing:
var second = myArray;
We are pointing the variable second to myArray memory location. Here new Object second will be created point to content of myArray. So, if you read content of second. It will read the myArray. But, you edit/update the content of second, content of myArray will be copied into second and it will be modified. As Bakudan said, It is the shallow copy. See the example below,
var myArray=[10,20,30];
var second =myArray; //second will contain 23,45 and 100.
If we update the array second, second=[100,200,300]
Original contents will be cleaned and 100,200,300 will be written.
To append the content to array second without removing the original content, We need to use function push as below:
second.push(100);second.push(200),second.push(300);
Now, content of second will be 10,20,30,100,200,300.
Object Property:
second.target = "testString";
second.offsetX =87;
second.offsetY =56;
This is the creation of object properties. It is same as,
second={"target":"testString","offsetX":87,"offsetY":56};
If you want to access value 87, it can be accessed as second.offsetX or second[offsetX].
More Information about java script Array is available here.

Pass associative array to Javascript function

How can I pass associative array in the below code. I dont wish to create a variable
uiDialog([MyURL,null,'GET'],false);
Some thing like this
uiDialog([url:MyURL,data:null,method:'GET'],false);
I know I can do something like
var arr = new Array(5);
arr["000"]="Rose";
arr["4"]="Ltd";
And pass this array but I am not interested in that I want a one line code
UPDATE
It seams there is no one line solution but if object is not a problem i.e u cant use array function or length you can try this answer Pass associative array to Javascript function
uiDialog({url:MyURL,data:null,method:'GET'},false);
var arr = new Array(3);
arr['url']=MyURL;
arr['data']=null;
arr['method']='GET';
uiDialog(arr,false);

Categories