Array sorting creating linked arrays? - javascript

I am creating a Chrome extension and am getting some weird results with sorted arrays. I have two global arrays called "timearray" and "timearrayorig" (timearray is the sorted version of timearrayorig). In a function, I set a bunch of values in timearrayorig and then copy the entire array to timearray and sort timearray. For some reason, this also sorts timearrayorig. I would greatly appreciate it if someone could explain why this is the case.
for (var i = 0; i < triparray.length; i++) {
for (var j = 0; j < trainsfeed.length; j++) {
if (trainsfeed[j].getElementsByTagName('Trip')[0].childNodes[0].nodeValue == triparray[i]) {
if (timearrayorig.length < i + 1 || timearrayorig[i] > Number(trainsfeed[j].getElementsByTagName('Scheduled')[0].childNodes[0].nodeValue)) {
timearrayorig.push(Number(trainsfeed[j].getElementsByTagName('Scheduled')[0].childNodes[0].nodeValue));
}
}
}
}
timearray = timearrayorig;
//timearray.sort();
(trainsfeed is a bunch of XML separated by messages and triparray is the list of all the different values for the "Trip" field. timearrayorig and timearray are the earliest times for each element of triparray from the elements of trainsfeed.)
If I run this script and find the value of timearrayorig and timearray in the debug console, they are the same, for example [1365801720, 1365801180, 1365801600, 1365802800, 1365800940]. But when I sort timearray, they both become [1365800940, 1365801180, 1365801600, 1365801720, 1365802800].

timearray = timearrayorig;
This doesn't copy the array; it creates a second variable which refers to the same array. There is still only one array, which is why sorting it affects both variables. To copy the array, do:
var timearray = timearrayorig.slice();
For more details, see: Copying array by value in JavaScript.

timearrayorig is holding a reference to the array, so when you assign timearray = timearrayorig; both labels reference the same memory space.
If you want to copy the array you can do something like:
timearray = [];
for(var i = 0; i < timearrayorig.length; i++) timerray[i] = timearrayorig[i];

Related

Two Dimensional Array - arr[i][0] Gives Wrong Result - JavaScript ASP.NET C#

I have an Array of Arrays populated from C# Model:
var AllObjectsArray = [];
#foreach(var Cobject in Model.ObjectList)
{
#:AllObjectsArray.push(new Array("#Cobject.Name", "#Cobject.Value", "#Cobject.Keyword"));
}
var SelectedObjects = [];
uniqueobj.forEach(function (element) {
SelectedObjects.push(new Array(AllObjectsArray.filter(elem => elem[0] === element))); //makes array of selected objects with their values(name,value,keyword)
});
I am trying to get second parameter of each and every inner Array and add it to new array containing those elements like this:
var ValuesArray = [];
for (i = 0; i < SelectedObjects.length; i++) {
ValuesArray.push(SelectedObjects[i][0]) //problem here i think
};
Unfortunately, on:
alert(ValuesArray + " : " + SelectedObjects);
I get nothing for ValuesArray. The other data for SelectedObjects loads properly with all three parameters correctly returned for each and every inner Array,so it is not empty. I must be iterating wrongly.
EDIT:
SOme more info as I am not getting understood what I need.
Lets say SelectedObjects[] contains two records like this:
{ name1, number1, keyword1}
{ name2, number2, keyword2}
Now, what I need is to populate ValuesArray with nane1 and name2.
That is why I was guessing I should iterate over SelectedObjects and get SelectedObject[i][0] where in my guessing i stands for inner array index and 1 stands for number part of that inner array. Please correct me and put me in the right direction as I am guesing from C# way of coding how to wrap my head around js.
However SelectedObject[i][0] gives me all SelectedObject with all three properties(name, value and keyword) and I should get only name's part of the inner Array.
What is happening here?
Hope I explained myself better this time.
EDIT:
I think I know why it happens, since SelectedObjects[i][0] returns whole inner Array and SelectedObjects[i][1] gives null, it must mean that SelectedObjects is not Array of Arrays but Array of strings concatenated with commas.
Is there a way to workaround this? SHould I create array of arrays ddifferently or maybe split inner object on commas and iteratee through returned strings?
First things first, SelectedObjects[i][1] should rather be SelectedObjects[i][0].
But as far as I understand you want something like
var ValuesArray = [];
for (let i = 0; i < SelectedObjects.length; i++) {
for(let j = 0; j <SelectedObjects[i].length; j++) {
ValuesArray.push(SelectedObjects[i][j]);
}
};
In this snippet
var ValuesArray = [];
for (i = 0; i < SelectedObjects.length; i++) {
ValuesArray.push(SelectedObjects[i][1]) //problem here i think
};
You're pointing directly at the second item in SelectedObjects[i]
Maybe you want the first index, 0

Appending an array with multiple arrays in google script

I have an array where I send a set of values after an operation on a spreadsheet followed by taking the average.
Now I want to return each row also along with the above data.
I thought of using two-dimensional arrays.
But I have less clarity in implementing this.
for (var i = 0; i < spreadsheetRows.length; i++)
{
//operations done and variables updated
variable1=
variable2=
variablen=
}
var sendArray = [];
sendArray.push(variable1);
sendArray.push(variable2);
sendArray.push(variable3);
sendArray.push(variable4);
return sendArray;
Now i want to send the array rowFirst & rowSecond also
for (var i = 0; i < spreadsheetRows.length; i++)
{
//first row of spreadsheet
rowFirst=[]; //data of first row
rowSecond=[]; //data of second row
//operations done and variables updated
variable1=
variable2=
variablen=
}
var sendArray = [];
sendArray.push(variable1);
sendArray.push(variable2);
sendArray.push(variable3);
sendArray.push(variable4);
sendArray.push(rowFirst); // stuck here <---
sendArray.push(rowSecond);// stuck here <----
return sendArray;
How to send the array with these two data( ie rowFirst and rowSecond) . Please guide me.
Output Expected
sendArray=[
var1,
var2,
var3,
varn,
rowFirst=[num1, num2, num3,...numn]
rowSeocnd=[num1, num2, num3,...numn]
]
To answer your immediate question, you can push an array into another array by using square brackets in push.
sendArray.push([rowFirst]);
sendArray.push([rowSecond]);
Based on your comment, you may want to use an Object, not an Array (here's a helpful article on the differences). So, think through why you'd want four variables not associated with anything. Can those be grouped or keyed somehow? There are a number of ways to do this and a simple method is to use dot notation to pair a variable or a data set to an object key.
// declare the object and each array
var sendObject = {}
// from your code...
for (var i = 0; i < spreadsheetRows.length; i++)
{
//operations done and variables updated
variable1=
variable2=
var rowFirst = [variable1, variable2, ...]
}
// Create the key in the Object and assign the array
sendObject.rowFirst = rowFirst;
The output would be:
sendObject = {
"rowFirst": [variable1, variable2, ...]
}

Google Sheets / Javascript -> Loop through array and set the values to the cells

I am new to programming and I have such a simple question but I struggle to find the answer. I would like to dynamically overwrite cells from A1 on until the lenght of the array. This is the second for loop I am struggling with. The combination of ("A" + ii) for the range doesnt look "professional" :-)
Thanks for your help.
function selectmyagency() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var agencynames = ss.getRange("B8:B42").getValues();
var myagency = ss.getRange("C3").getValue();
var arrayLength = agencynames.length;
for (var i = 0; i < arrayLength; i++) {
if(agencynames[i] == myagency){
//doNothing
} else {
agencynames[i] = ".";
}//endif
}//endfor
//overwrite Cell in Spreadsheet
for (var ii = 0; ii < agencynames.length; ii++) {
SpreadsheetApp.getActiveSheet().getRange("A"+ii).setValue(agencynames[ii]);
//SpreadsheetApp.getActiveSheet().getRange("A9").setValue(agencynames[ii]);
//SpreadsheetApp.getActiveSheet().getRange("A10").setValue(agencynames[ii]);
}
}//endfunction
Instead of looping through the array and setting the ranges value one cell at a time, you can do this in a batch operation like so: ss.getRange("B8:B42").setValues(agencynames);
Do this after modifying the agencynames array, this will set all the values of that range to match your array as long as the array and the range are the same size. It's generally discouraged to make calls to a service in a loop when you can use a batch operation, for performances and readabilities sake.
For more information, refer to the Apps Script Best Practices
Edit: Your modified code:
function selectmyagency() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var agencynames = ss.getRange("B8:B42").getValues();
var myagency = ss.getRange("C3").getValue();
var arrayLength = agencynames.length;
for (var i = 0; i < arrayLength; i++) {
if(agencynames[i] == myagency){
//doNothing
} else {
agencynames[i] = ".";
}//endif
}//endfor
//overwrite Cell in Spreadsheet
ss.getRange("B8:B42").setValues(agencynames);
}//endfunction
A couple more pointers:
There is no need to set an array length variable if you are only modifying the elements themselves and not the array.
When you use getValues() you are getting an array of arrays not an array of values, even if it is only a single column. ie. [["value"],["value"],["value"]] instead of ["value","value","value"]. When setting or getting the values of this array, you probably want to useagencynames[i][0] instead of agencynames[i]

Loading JSON array from API into another array in Javascript using a loop

I'm pretty new to programming in general but have the problem that my array keeps being overwritten in my for loop so when I print in to the console only the last set of data is showing. i.e the data in the array is overwritten each time.
I want to store all the details in an array so I can work with the data. I have tried to put an array into an array but keep getting errors.
for (var i = 0; i < collection.length; i++){
var dailyfxTech = [];
dailyfxTech.push((collection[i].ccyPair), (collection[i].resistance), (collection[i].support), (collection[i].trend.src));
}
console.log(dailyfxTech)
How can I append the data to the dailyfxTech array each time it loops so that it looks like ;
dailyFxTech {[ccypair], [resistance], [support], [trend.src]},
{[ccypair], [resistance], [support], [trend.src]},
{[ccypair], [resistance], [support], [trend.src]},
{[ccypair], [resistance], ...etc},
I later want to be able to reference the array to place the data in other parts of my site eg:
dailyFxTech[2,3] = the support of third ccy pair.
Thank you for your help.
Your issue is that each time the loop is running you are declariing a new array. Super simple fix. Just need to put the var dailyfxTech outside of your loop.
var dailyfxTech = [];
for (var i = 0; i < collection.length; i++){
dailyfxTech.push((collection[i].ccyPair), (collection[i].resistance), (collection[i].support), (collection[i].trend.src));
}
console.log(dailyfxTech)
Declare var dailyFxTech outside of the for loop.
var dailyfxTech = [];
for (var i = 0; i < collection.length; i++){
dailyfxTech.push((collection[i].ccyPair), (collection[i].resistance), (collection[i].support), (collection[i].trend.src));
}
When you have the var declaration in the body of the for loop, the variable is re-allocated and the old value is trashed.

cannot iterate through array and change value in JS

I have to iterate through an array, change one of its values, and create another array refelecting the changes.
this is what I have so far:
JS:
var arr = new Array();
arr['t1'] = "sdfsdf";
arr['t2'] = "sdfsdf";
arr['t3'] = "sdfsdf";
arr['t4'] = "sdfsdf";
arr['t5'] = "sdfsdf";
var last = new Array();
for (var i = 0; i <= 5; i++) {
arr['t2'] = i;
last.push(arr);
}
console.log(last);
Unfortunately, these are my results
As you can see, I am not getting the results needed as 0,1,2.. instead I am getting 2, 2, 2..
This is what i would like my results to be:
How can I fix this?
You have to make a copy, otherwise you are dealing with reference to the same object all the time. As it was said before - javascript does not have associate arrays, only objects with properties.
var arr = {}; // empty object
arr['t1'] = "sdfsdf";
arr['t2'] = "sdfsdf";
arr['t3'] = "sdfsdf";
arr['t4'] = "sdfsdf";
arr['t5'] = "sdfsdf";
var last = new Array();
for (var i = 0; i <= 5; i++) {
var copy = JSON.parse(JSON.stringify(arr)); //create a copy, one of the ways
copy['t2'] = i; // set value of its element
last.push(copy); // push copy into last
}
console.log(last);
ps: you can use dot notation arr.t1 instead of arr['t1']
The array access with ['t2'] is not the problem. This is a regular JavaScript feature.
The problem is: You are adding the SAME array to "last" (5 times in code, 3 times in the screenshot).
Every time you set ['t2'] = i, you will change the values in "last" also, because they are actually just references to the same array-instance.
You must create a copy/clone of the array before you add it to "last".
This is what will happen in all languages where arrays are references to objects (Java, C#...). It would work with C++ STL though.

Categories