How to convert variable to two dimensional array using java script - javascript

I have a variable which contains data like this
var values = "VItDTotal,123,234,234,2345,1234,123,435,10,TestCase,123,234,234,2345,1234,123,435,5"
and I want to convert this string of data to a two dimensional array like this
[VItDTotal,123,234,234,2345,1234,123,435,10] //1st row
[TestCase, 123,234,234,2345,1234,123,435,5] //2nd row
How can I convert a JS variable to a two dimensional array?
I want to append these values to a datatable, how can I achieve this by using jQuery?

I hope this might help...
var values = "VItDTotal,123,234,234,2345,1234,123,435,10,TestCase,123,234,234,2345,1234,123,435,5"
var splittedArray = values.split(',')
var resultArray = new Array();
var resultKey = -1;
for(var i=0; i<splittedArray.length; i++) {
if(isNaN(splittedArray[i])) {
resultKey++;
resultArray[resultKey] = new Array();
resultArray[resultKey].push(splittedArray[i])
} else {
resultArray[resultKey].push(splittedArray[i])
}
}

I work this way:
//get the index where ",TestCase" is
var index = values.indexOf(",TestCase");
//create two arrays to the values
var part_one = [], part_two = [];
//slice the value from 0 to index and push part one
part_one.push(values.slice(0,index));
//slice the value from index+1 to the end and push part two
part_two.push(values.slice(index+1, values.length));

Not my favourite, but, are you after something like this?
var values = ["VItDTotal",123,234,234,2345,1234,123,435,10,"TestCase",123,234,234,2345,1234,123,435,5];
var vals = [values.
join(",").
replace(/,([a-z]+)(?!.*[a-z]+)/gi, " devider $1").
split(/\s+devider\s+/gi)];
console.log(vals);

Related

How to get the all the values in multiple columns and store them in one variable

I'm trying to get the values of 4 columns (N, P, R, T) and store them in one column.
Also, I thought of doing the same thing but for rows ( So like concatenate 4 cells in 4 columns and store them in a variable via a for loop). I think I would start doung that when I figure the columns first.
for example:-
so here i want to store the values of each column and store them in one variable and then sum all 4 values to get the value of all four columns which is (14+12+11+7) which is 44.
I wrote this code but it doesn't seem to me like its storing the values.
function percentage(){
const thisSheet = SpreadsheetApp.openByUrl(THIS).getSheetByName('WP_Data');
var range=thisSheet.getRangeList(['N3:N', 'P3:P', 'R3:R', 'T3:T']);
var rangeN= thisSheet.getRange("N3:N");
var valueN=rangeN.getValues();
var rangeP= thisSheet.getRange("P3:P");
var valueP=rangeP.getValues();
var rangeR= thisSheet.getRange("R3:R");
var valueR=rangeR.getValues();
var rangeT= thisSheet.getRange("T3:T");
var valueT=rangeT.getValues();
console.log()
var val =valueN + valueP + valueR + valueT;
}
would really appreciate the help.
If you need more info please let me know
This might do the works for you
function percentage(){
const thisSheet = SpreadsheetApp.openByUrl(THIS).getSheetByName('WP_Data');
var range=ss.getRangeList(['N3:N', 'P3:P', 'R3:R', 'T3:T']);
var rangeN= ss.getRange("N3:N");
var valueN=rangeN.getValues();
var rangeP= ss.getRange("P3:P");
var valueP=rangeP.getValues();
var rangeR= ss.getRange("R3:R");
var valueR=rangeR.getValues();
var rangeT= ss.getRange("T3:T");
var valueT=rangeT.getValues();
//you can use concat or creat a new array to store these values.
const array = valueN.concat(valueP,valueR,valueT).flat();
//then use array.reduce function to sum all the items in the array.
const sum = array.reduce((value,sum) => value+sum)
// you will get the out put as 44
console.log(sum)
}
Is that what you asking for?
const string = array.toString();
console.log(string)
Something like this?
function percentage(){
const thisSheet = SpreadsheetApp.openByUrl(THIS).getSheetByName('WP_Data');
var values = thisSheet.getRange(3,14,thisSheet.getLastRow()-2,7).getValues(); // N3:T??
var results = [];
var i = 0;
for( i=0; i<values.length; i++ ) {
results.push([values[i][0]+values[i][2]+values[i][4]+values[i][6]]); // index 0 = column N, etc.
}
// don't know what you want to do with it but you could use setValues(results)
thisSheet.getRange(??,??,results.length,1).setValues(results);
}

iterating over an array while copying only integers to another in js

I have tried iterating over the array holder2 while copying it's integer elements to another array temp. But it doesn't seem to work as the content of temp remained the same.
var holder=getElementById("userinput").value;
var holder2=holder.split(" ");
var temp =[];
for(vari=0;i<holder2.length;i++){
if(isNaN(holder2[i])===false){
temp[i]=holder2[i];
}
}
That's not how you add an element to an array in Javascript. What you're looking for is push().
temp.push(holder2[i]);
You mentioned that you want integers only and that temp is empty. I'd suggest verifying that elements are integers and then using Array.push().
var holder=getElementById("userinput").value;
var holder2=holder.split(" ");
var temp =[];
for(var i=0;i<holder2.length;i++){
if(isNaN(holder2[i])===false && holder2[i] % 1 === 0){
temp.push(holder2[i]);
}
}
Try this:
var holder=getElementById("userinput").value;
var holder2=holder.split(" ");
var temp =[];
for(var i=0;i<holder2.length;i++){
var num = parseInt(holder2[i])
if(isNaN(num)===false){
temp.push(num)
}
}

Adding for loop results to an array and displaying sum of added elements after the last loop

I have to get some records based on weekly basis for the last weeks, and have to add values from records of one week to an array. So, I declared 6 arrays to store 6 weeks records. My code is:
var w_0 = [];var w_1 = [];var w_2 = [];var w_3 = [];var w_4 = [];var w_5 = [];
var myTotal = 0;
var arr_name = "";
for(var j=0;j<=5;j++)
{
var start_date="";
var end_date="";
//code to fetch the records added between start_date,end_date
//there may be more that one record
var count = getRecordCount(); //My function
//following loop is to fetch value from a record
for(var i=0;i<count;i++)
{
var val1 = getRecordByIndex(i).getValue("rem_val"); //getRecordByIndex() and getValue() are our pre-defined functions.
//here I want to push the values into the array w_0
arr_name = "w_"+j;
[arr_name].push(val1); //this is not working
alert([arr_name]); //showing 'w_0'
}
//and here I want to sum all the array elements when i reaches its maximum
for(var a=0;a<[arr_name].length; a++){
myTotal += parseInt([arr_name][a]);
}
alert("Total value of week"+j+"="+parseInt(myTotal));
}
How can I add values of inner loop to the array based on outer loop?
Any time you find yourself creating variables with sequentially numbered names, you should probably be using an array instead.
var w = [[], [], [], [], []];
Then, wherever you tried to use [arr_name] to refer to a particular w_j variable, you should use w[j].
for(var j=0;j<=w.length;j++)
{
var cur_w = w[j];
var start_date="";
var end_date="";
//code to fetch the records added between start_date,end_date
//there may be more that one record
var count = getRecordCount(); //My function
//following loop is to fetch value from a record
for(var i=0;i<count;i++)
{
var val1 = getRecordByIndex(i).getValue("rem_val"); //getRecordByIndex() and getValue() are our pre-defined functions.
cur_w.push(val1);
alert(cur_w);
}
//and here I want to sum all the array elements when i reaches its maximum
for(var a=0;a<cur_w.length; a++){
myTotal += parseInt(cur_w[a]);
}
alert("Total value of week"+j+"="+parseInt(myTotal));
}
If you want to dynamically manipulate global variables you can use window prefix:
arr_name = "w_"+j;
window[arr_name].push(val1); // This should work

Dynamically create a two dimensional Javascript Array

Can someone show me the javascript I need to use to dynamically create a two dimensional Javascript Array like below?
desired array contents:
[["test1","test2","test3","test4","test5"],["test6","test7","test8","test9","test10"]]
current invalid output from alert(outterArray):
"test6","test7","test8","test9","test10","test6","test7","test8","test9","test10"
JavaScript code:
var outterArray = new Array();
var innerArray = new Array();
var outterCount=0;
$something.each(function () {
var innerCount = 0;//should reset the inner array and overwrite previous values?
$something.somethingElse.each(function () {
innerArray[innerCount] = $(this).text();
innerCount++;
}
outterArray[outterCount] = innerArray;
outterCount++;
}
alert(outterArray);
This is pretty cut and dry, just set up a nested loop:
var count = 1;
var twoDimensionalArray =[];
for (var i=0;i<2;i++)
{
var data = [];
for (var j=0;j<5;j++)
{
data.push("Test" + count);
count++;
}
twoDimensionalArray.push(data);
}
It sounds like you want to map the array of text for each $something element into an outer jagged array. If so then try the following
var outterArray = [];
$something.each(function () {
var innerArray = [];
$(this).somethingElse.each(function () {
innerArray.push($(this).text());
});
outterArray.push(innerArray);
});
alert(outterArray);
A more flexible approach is to use raw objects, they are used in a similar way than dictionaries. Dynamically expendables and with more options to define the index (as string).
Here you have an example:
var myArray = {};
myArray[12]="banana";
myArray["superman"]=123;
myArray[13]={}; //here another dimension is created
myArray[13][55]="This is the second dimension";
You don't need to keep track of array lengths yourself; the runtime maintains the ".length" property for you. On top of that, there's the .push() method to add an element to the end of an array.
// ...
innerArray.push($(this).text());
// ...
outerArray.push(innerArray);
To make a new array, just use []:
innerArray = []; // new array for this row
Also "outer" has only one "t" :-)
[SEE IT IN ACTION ON JSFIDDLE] If that $something variable is a jQuery search, you can use .map() function like this:
var outterArray = [];
var outterArray = $('.something').map(function() {
// find .somethingElse inside current element
return [$(this).find('.somethingElse').map(function() {
return $(this).text();
}).get()]; // return an array of texts ['text1', 'text2','text3']
}).get(); // use .get() to get values only, as .map() normally returns jQuery wrapped array
// notice that this alert text1,text2,text3,text4,text5,text6
alert(outterArray);​
// even when the array is two dimensional as you can do this:
alert(outterArray[0]);
alert(outterArray[1]);
HTML:
<div class="something">
<span class="somethingElse">test1</span>
<span class="somethingElse">test2</span>
<span class="somethingElse">test3</span>
</div>
<div class="something">
<span class="somethingElse">test4</span>
<span class="somethingElse">test5</span>
<span class="somethingElse">test6</span>
</div>
Here you can see it working in a jsFiddle with your expected result: http://jsfiddle.net/gPKKG/2/
I had a similar issue recently while working on a Google Spreadsheet and came up with an answer similar to BrianV's:
// 1st nest to handle number of columns I'm formatting, 2nd nest to build 2d array
for (var i = 1; i <= 2; i++) {
tmpRange = sheet.getRange(Row + 1, Col + i, numCells2Format); // pass/fail cells
var d2Arr = [];
for (var j = 0; j < numCells2Format; j++) {
// 1st column of cells I'm formatting
if ( 1 == i) {
d2Arr[j] = ["center"];
// 2nd column of cells I'm formatting
} else if ( 2 == i ) {
d2Arr[j] = ["left"];
}
}
tmpRange.setHorizontalAlignments( d2Arr );
}
So, basically, I had to make the assignment d2Arr[index]=["some string"] in order to build the multidimensional array I was looking for. Since the number of cells I wanted to format can change from sheet to sheet, I wanted it generalized. The case I was working out required a 15-dimension array. Assigning a 1-D array to elements in a 1-D array ended up making the 15-D array I needed.
you can use Array.apply
Array.apply(0, Array(ARRAY_SIZE)).map((row, rowIndex) => {
return Array.apply(0, Array(ARRAY_SIZE)).map((column, columnIndex) => {
return null;
});
});`

attempting to convert String data into numerical data, the drop the data into an array of arrays (Json)

I have this:
(65.94647177615738, 87.890625)(47.040182144806664, 90)(45.089035564831036, 122.34375)
I'm attempting to get the output to look like this:
"coords": [[65.94647177615738, 87.890625],[47.040182144806664, 90],[45.089035564831036, 122.34375]]
Any Idea?
The first result comes back to me as a string, so when i try to assign the first object to an array, the console shows me this:
array is: "(65.94647177615738, 87.890625)(47.040182144806664, 90)(45.089035564831036, 122.34375)"
var str = "(65.94647177615738, 87.890625)(47.040182144806664, 90)(45.089035564831036, 122.34375)";
str = str.slice(1,-1); // remove outermost parentheses
var arrCoord = str.split(')(');
for (var i=0; i<arrCoord.length; i++) {
var tarr = arrCoord[i].split(", ");
for (var j=0; j<tarr.length; j++) {
tarr[j] = parseFloat(tarr[j]);
}
arrCoord[i] = tarr;
}
// arrCoord is now populated with arrays of numbers
Decided to sort of play code golf. Assuming:
var sample = '(65.94647177615738, 87.890625)(47.040182144806664, 90)(45.089035564831036, 122.34375)';
Then:
var coords = sample
.split(/\(([^)]+)\)/)
.filter(function(v){return v!=""})
.map(function(v){return v.split(/[^0-9\.]+/)})

Categories

Resources