for (var i = 0; i < featureSet.features.length; i++) {
for (var f = 0, f1 = featureTracts.length; f < f1; f++) {
rows["Sensor"] = featureTracts[f].attributes.Sensor;
rows["Resolution"] = featureTracts[f].attributes.Resolution;
rows["Dtofparse"] = featureTracts[f].attributes.Dtofparse;//PATH_ROW
// alert(rows);
}
resosat1[i] = rows;
}
i am trying to print all values in resosat1[i] array but it will take only last value and all values overwirite and update only last value to array
for (var i = 0; i < featureSet.features.length; i++) {
var rowAaaray = [];
for (var f = 0, f1 = featureTracts.length; f < f1; f++) {
var rows = {};
rows["Sensor"] = featureTracts[f].attributes.Sensor;
rows["Resolution"] = featureTracts[f].attributes.Resolution;
rows["Dtofparse"] = featureTracts[f].attributes.Dtofparse;//PATH_ROW
// alert(rows);
rowAaaray.push(rows);
}
resosat1[i] = rowAaaray;
}
}
Because you are maintaining one variable and overriding it in loop. So you will get last overwritten object only.
I agree with the guy in the comment. Try:
for (var i = 0; i < featureSet.features.length; i++) {
for (var f = 0, f1 = featureTracts.length; f < f1; f++) {
rows["Sensor"] = featureTracts[f].attributes.Sensor;
rows["Resolution"] = featureTracts[f].attributes.Resolution;
rows["Dtofparse"] = featureTracts[f].attributes.Dtofparse;//PATH_ROW
resosat1[f] = rows; <======== THIS WILL STORE THE VALUE OF EACH ROW CREATED
}
<==//TRY STORING THE resosat1 array In another array here instead.
//eg. arrayEx[i]=resosat1
//Alternatively, you could use a 2D Array eg. arrayEx[i][f]
}
Hope this helps you out.
try this one..
for (var i = 0; i < featureSet.features.length; i++) {
var arr = []; // create array
for (var f = 0, f1 = featureTracts.length; f < f1; f++) {
var rows = {};
rows["Sensor"] = featureTracts[f].attributes.Sensor;
rows["Resolution"] = featureTracts[f].attributes.Resolution;
rows["Dtofparse"] = featureTracts[f].attributes.Dtofparse;//PATH_ROW
// alert(rows);
arr.push(rows);
}
resosat1[i] = arr;
}
}
rows is undeclared (at least in your snippet).
On the other hand, putting var rows = {}, as some suggest, will fix your problem because it creates new object each time. But, if your javascript version accepts it, it would be better to declare it wit let because, this way, you will be really creating new fresh variable (in block scope).
Declaring rows in an outer block will not fix your problem because you will be assigning same object during the whole loop.
Related
I'm working from the solution provided HERE to compare two arrays. The example provided returns values found in both arrays to Array1 (same) and values only found on one or the other two Array2 (diff).
ISSUE: When I apply it to my own script, valuesDATA returns nothing and valuesCheckSeeding returns ALL values from both arrays
DESIRED RESULT: I have two arrays that I'd either like to create a third out of, or only select values from the first array, valuesDATA which are NOT present in the second, valuesCheckSeeding. Using the solution above, I was trying to have all values not found in valuesCheckSeeding AND valuesDATA pushed to valuesDATA.
SAMPLE OF valuesDATA: "U09 F
Harford FC Hill/Healey - A
MD
CMSA Girls Saturday U09 A/B North
Premier - Top
TID0118"
What am I doing wrong? I tinkered with changing matchfound==false and matchfound=true in the loop, but that still didn't give me the desired result.
MOST RELEVANT SNIPPET
var matchfound = false;
for (var i = 0; i < valuesDATA.length; i++) {
matchfound=false;
for (var j = 0; j < valuesCheckSeeding.length; j++) {
if (valuesDATA[i] == valuesCheckSeeding[j]) {
valuesCheckSeeding.splice(j, 1);
matchfound=true;
continue;
}
}
if (matchfound==false) {
valuesCheckSeeding.push(valuesDATA[i]);
valuesDATA.splice(i, 1);
i=i-1;
}
}
WORKIG SCRIPT EDITED FROM COMMENTS/ANSWERS BELOW
//UPDATE SEEDING SHEET
function updateSeedingSheet() {
var today = Utilities.formatDate(new Date(),Session.getScriptTimeZone(), "MM/dd/yyyy hh:mm a");
//INPUT SHEET INFO
var inputCurrentRow = 4;
var inputCurrentColumn = 20;
var inputNumRows = 1000;
var inputNumColumns =1;
var ssInput = SpreadsheetApp.openById('1Wzg2BklQb6sOZzeC0OEvQ7s7gIQ07sXygEtC0CSGOh4');
var sheetDATA = ssInput.getSheetByName('DATAREF');
var rangeDATA = sheetDATA.getRange(inputCurrentRow, inputCurrentColumn, inputNumRows, inputNumColumns);
var valuesDATA = rangeDATA.getValues();
//SEEDING SHEET INFO
var seedingCurrentRow = 4;
var seedingCurrentColumn = 1;
var seedingNumRows = 1000;
var seedingNumColumns = 1;
var ssSeeding = SpreadsheetApp.openById('1DuCHeZ3zba-nHq-7vYTrylncPGqcA1J9jNyW9DaS3mU');
var sheetSeeding = ssSeeding.getSheetByName('Seeding');
var rangeCheckSeeding = sheetSeeding.getRange(4, 102, 1000, 1);
var columnToClear = sheetSeeding.getRange(seedingCurrentRow, seedingCurrentColumn, seedingNumRows, seedingNumColumns);
var valuesCheckSeeding = rangeCheckSeeding.getValues();
//METHOD TO FILTER
valuesCheckSeeding = valuesCheckSeeding.map(function(e){return e[0];}); //flatten this array
var filteredArr = valuesDATA.filter(function(e){
return !(this.indexOf(e[0])+1);
},valuesCheckSeeding);
Logger.log(filteredArr);
Logger.log(filteredArr.length);
var rangeSeeding = sheetSeeding.getRange(seedingCurrentRow, seedingCurrentColumn, filteredArr.length, seedingNumColumns);
sheetSeeding.getRange('A1').setValue(today);
columnToClear.clearContent();
rangeSeeding.setValues(filteredArr);
/*
//ALTERNATIVE METHOD USING LOOPS
for (var i = 0; i < valuesDATA.length; i++) {
for (var j = 0; j < valuesCheckSeeding.length; j++) {
if (valuesDATA[i][0] == valuesCheckSeeding[j][0]) {
valuesDATA.splice(i, 1);
i--; //account for the splice
break; //go to next i iteration of loop
}
}
}
Logger.log("VALUES DATA:" + valuesDATA);
Logger.log("VALUES CHECK SEEDING: " + valuesCheckSeeding);
//sheetSeeding.getRange('A1').setValue(today);
//rangeSeeding.clearContent();
//rangeSeeding.setValues(valuesDATA); //INCORRECT RANGE HEIGHT, WAS 71 BUT SHOULD BE 1000 - Is splice affecting this?
*/
}//END FUNCTION
V8(ES2016 update):
You can use newer and efficient set class
const array1 = [[1],[2],[3]],
array2 = [[1],[3],[4]],
set = new Set(array2.flat())
console.info(array1.filter(e => !set.has(e[0])))
//expected output [[2]]
You're checking a 2D array. You'd need to use [i][0] and [j][0]
You can try only splicing valuesDATA
Try
for (var i = 0; i < valuesDATA.length; i++) {
for (var j = 0; j < valuesCheckSeeding.length; j++) {
if (valuesDATA[i][0] == valuesCheckSeeding[j][0]) {
valuesDATA.splice(i, 1);
i--; //account for the splice
break; //go to next i iteration of loop
}
}
}
Logger.log(valuesDATA);
Alternatively, try
valuesCheckSeeding = valuesCheckSeeding.map(function(e){return e[0];}); //flatten this array
var filteredArr = valuesDATA.filter(function(e){
return !(this.indexOf(e[0])+1);
},valuesCheckSeeding);
Logger.log(filteredArr);
I create multiple objects and push them to the array objArr:
var objArr = [];
var obj = {};
var height = [9,8,7,3,6,5,2,4];
for (var i = 0; i < 8; i++) {
debugger;
var mountainH = height[i];
obj.h = mountainH;
obj.index = i;
objArr.push(obj);
}
for (var i = 0; i < objArr.length; i++) {
alert(objArr[i].h);
}
But as you can see, each object has the same values. Why?
Put the initialization of obj within your for-loop.
You were re-assigning new values to a global variable obj.
var objArr = [];
var height = [9,8,7,3,6,5,2,4];
for (var i = 0; i < 8; i++) {
debugger;
var obj = {};
var mountainH = height[i];
obj.h = mountainH;
obj.index = i;
objArr.push(obj);
}
for (var i = 0; i < objArr.length; i++) {
console.log(objArr[i].h);
}
Because the scope of obj in your code is global and it should rather be contained in the for loop.
If you will not declare it inside the loop then the value will get overwritten of the same obj on each iteration instead of a new memory allocation.
var objArr = [];
var height = [9, 8, 7, 3, 6, 5, 2, 4];
for (var i = 0; i < 8; i++) {
debugger;
var mountainH = height[i];
var obj = {};
obj.h = mountainH;
obj.index = i;
objArr.push(obj);
}
console.log(obj);
As noted, you need to initialize a new object in each iteration of the loop, otherwise all your array members simply share the same object reference.
Additionally, your code can be greatly reduced by building the array using .map(), and fully using the object literal initializer to declare the properties.
var height = [9,8,7,3,6,5,2,4];
var objArr = height.map((n, i) => ({h: n, index: i}));
console.log(objArr);
This is shorter and clearer. For every number in height, it creates a new object and adds it to a new array, which is returned from .map().
It can be even a little shorter with the newer features for object literals.
var height = [9,8,7,3,6,5,2,4];
var objArr = height.map((h, index) => ({h, index}));
console.log(objArr);
Apologies if this has been asked before - I couldn't find what I was looking for after a search, but I'm a beginner, so I might have missed something.
I am trying to implement Lloyd's algorithm in JavaScript (very crudely) to get some practice.
var k_means = function (array,number_clusters,max_loops) {
var initial_centers = underscore.sample(shelter_lat_lon,number_clusters);
var current_centers = initial_centers;
var current_associations = {};
for (p = 0; p < current_centers.length; p++) {
current_associations[current_centers[p]] = []
}
for (loops = 0; loops < max_loops; loops++) {
for (i = 0; i < array.length; i++) {
var current_loc = array[i]
temp_array = new Array();
for (j = 0; j < current_centers.length; j++) {
var distance_from_center = distance(current_centers[j],current_loc)
temp_array.push(distance_from_center)
}
var closest_center_lat_lon = current_centers[smallest_index(temp_array)]
current_associations[closest_center_lat_lon].push(current_loc)
}
new_clusters_temp = []
for (var key in current_associations) {
lat = []
lon = []
for (i = 0; i < current_associations[key].length; i++){
lat.push(current_associations[key][i][0])
lon.push(current_associations[key][i][1])
}
mean_lat = math_module.mean(lat)
mean_lon = math_module.mean(lon)
new_clusters_temp.push([mean_lat,mean_lon])
}
current_centers = new_clusters_temp;
}
}
Sorry for the ugly code. There are 2 module requirements - underscore and mathjs (mathjs is called math_module). Additionally, the function distance returns the Euclidean distance (I'm using 2 dimensional data), and smallest_index returns the index of the smallest element in an array.
The only problem I'm having is coming at the line
current_centers = new_clusters_temp;
Node returns the error "Cannot read property 'push' of undefined." After debugging a bit, it essentially thinks the array "current_centers" is empty. In Python, this is how I would reassign a list outside of a for loop. Is this different in JavaScript?
Cheers!
Alex
I'm working on Google Script and I'm testing different ways to create two dimensions arrays.
I have created an array like this:
var codes = new Array(6);
for (var i = 0; i < 6; i++) {
codes[i] = new Array(4);
}
codes[0][0]="x";
codes[0][1]="x";
codes[0][2]="x";
codes[0][3]="x";
codes[1][0]="x";
codes[1][1]="x";
codes[1][2]="x";
codes[1][3]="x";
codes[2][0]="x";
codes[2][1]="x";
codes[2][2]="x";
codes[2][3]="x";
codes[3][0]="x";
codes[3][1]="x";
codes[3][2]="x";
codes[3][3]="x";
codes[4][0]="x";
codes[4][1]="x";
codes[4][2]="x";
codes[4][3]="x";
codes[5][0]="x";
codes[5][1]="x";
codes[5][2]="x";
codes[5][3]="x";
And it is working fine.
I read following links here, here and here.
But when I do it like this:
var codes = new Array(6);
for (var i = 0; i < 6; i++) {
codes[i] = new Array(4);
}
codes[0]=["x","x","x","x"];
codes[1]=["x","x","x","x"];
codes[2]=["x","x","x","x"];
codes[3]=["x","x","x","x"];
codes[4]=["x","x","x","x"];
codes[5]=["x","x","x","x"];
It didn't work, so I tried like this:
var codes = new Array([["x","x","x","x"],["x","x","x","x"],["x","x","x","x"],["x","x","x","x"],["x","x","x","x"],["x","x","x","x"]]);
it didn't work either.
When the code don't work, I get no error, just no display of the values.
What am I doing wrong? It looks to be the same code and the two not working ways are recommended in many documentations.
W3schools says that there is no need to use new Array().
For simplicity, readability and execution speed, use literal method ex:
var animals = ["cat", "rabbit"];
Reason why your code was not working is that you're equaling codes inside the loop and after end of loop scope 'codes' is getting only the last set array. Instead you should push those arrays to codes.
var codes = [];
for (var i = 0; i < 6; i++) {
codes.push([i]);
}
console.log(codes)
codes[0]=["x","x","x","x"];
codes[1]=["x","x","x","x"];
codes[2]=["x","x","x","x"];
codes[3]=["x","x","x","x"];
codes[4]=["x","x","x","x"];
codes[5]=["x","x","x","x"];
Better yet, two for loops to create the double array:
var codes = [], // Initiate as array, in Javascript this is actually fastre than using new (I don't know any cases you should use new)
rows = 6,
columns = 6;
for (var i = 0; i < rows; i++){
codes.push([]); // Initiate
for (var j = 0; j < columns; j++){
codes[i][j] = 'x';
}
}
Other idea, pre-initiate an array with the correct columns then copy:
var arrTemp = [],
codes = [],
rows = 6,
columns = 6;
for (var j = 0; j < columns; j++)
arrTemp[i] = 'x';
for (var i = 0; i < rows; i++)
codes.push( arrTemp.slice(0) ); // If you just push the array without slice it will make a reference to it, not copy
Other way to pre-initiate the array with 'x's:
arrTemp = Array.apply(null, Array(columns)).map(function () {return 'x'});
function split(str)
{
var array = str.split(';');
var test[][] = new Array();
for(var i = 0; i < array.length; i++)
{
var arr = array[i].split(',');
for(var j = 0; j < arr.length; j++)
{
test[i][j]=arr[j];
}
}
}
onchange="split('1,2,3;4,5,6;7,8,9;a,b,c;d,e,f;g,h,i')"
it was not working. i need to split this string to 6*3 multi dimentional array
var array[][] = new Array() is not valid syntax for declaring arrays. Javascript arrays are one dimensional leaving you to nest them. Which means you need to insert a new array into each slot yourself before you can start appending to it.
Like this: http://jsfiddle.net/Squeegy/ShWGB/
function split(str) {
var lines = str.split(';');
var test = [];
for(var i = 0; i < lines.length; i++) {
if (typeof test[i] === 'undefined') {
test[i] = [];
}
var line = lines[i].split(',');
for(var j = 0; j < line.length; j++) {
test[i][j] = line[j];
}
}
return test;
}
console.log(split('a,b,c;d,e,f'));
var test[][] is an invalid javascript syntax.
To create a 2D array, which is an array of array, just declare your array and push arrays into it.
Something like this:
var myArr = new Array(10);
for (var i = 0; i < 10; i++) {
myArr[i] = new Array(20);
}
I'll let you apply this to your problem. Also, I don't like the name of your function, try to use something different from the standards, to avoid confusion when you read your code days or months from now.
function split(str)
{
var array = str.split(';'),
length = array.length;
for (var i = 0; i < length; i++) array[i] = array[i].split(',');
return array;
}
Here's the fiddle: http://jsfiddle.net/AbXNk/
var str='1,2,3;4,5,6;7,8,9;a,b,c;d,e,f;g,h,i';
var arr=str.split(";");
for(var i=0;i<arr.length;i++)arr[i]=arr[i].split(",");
Now arr is an array with 6 elements and each element contain array with 3 elements.
Accessing element:
alert(arr[4][2]); // letter "f" displayed