Hello my fellow JS friends,
I am letting a user import a csv file (excel sheet) and i convert that into
an array. which has 472 rows and 87 columns in this case.
so my array looks like this:
and everything is separated by commas like a usual array.
The issue is I need to separate the array within the array and when i do that i get an array with the length of 9 million, which i think is wrong
vm.allTextLines = files.split(/\r\n|\n/);
var headers = vm.allTextLines[0].split(',');
vm.columnCount = headers.length;
vm.rowCount = vm.allTextLines.length - 1;
for (var i = 0; i < vm.allTextLines.length; i++) {
// split content based on comma
var data = vm.allTextLines[i].split(',');
if (data.length == headers.length) {
var tarr = [];
for (var j = 0; j < headers.length; j++) {
tarr.push(data[j]);
}
vm.lines.push(tarr);
}
}
//this is where i split the array that contains the csv
//data and put it into its own array I believe this is
//where the issue is.
for(var i=1;i<vm.allTextLines.length; i++){
vm.uniqueAll.push(vm.allTextLines[i].split(','));
for(var j=0; j < vm.uniqueAll.length; j++){
for(var r =0; r < vm.uniqueAll[j].length; r++){
vm.arrayOfValuesOfFile.push(vm.uniqueAll[j][r]);
}
}
}
If you can help me correct this for each I would appreciate it alot.
Thank you in advance guys!
I agree with you about the place of error, because it seems you nested the loop in a wrong way. Following a snippet where you can check what I mean.
i.e:
let vm = {
allTextLines:['h1,h2,h3','row1val1,row1val2,row1val3', 'row2val1,row2val2,row2val3'],
uniqueAll: [],
arrayOfValuesOfFile:[]
}
// Here you should not nest the loop
for(var i=1;i<vm.allTextLines.length; i++){
vm.uniqueAll.push(vm.allTextLines[i].split(','));
}
for(var j=0; j < vm.uniqueAll.length; j++){
for(var r =0; r < vm.uniqueAll[j].length; r++){
vm.arrayOfValuesOfFile.push(vm.uniqueAll[j][r]);
}
}
console.log('allTextLines', vm.allTextLines);
console.log('uniqueAll', vm.uniqueAll);
console.log('arrayOfValuesOfFile', vm.arrayOfValuesOfFile);
Of Course you could easily optimize the algorithm:
let vm = {
allTextLines:['h1,h2,h3','row1val1,row1val2,row1val3', 'row2val1,row2val2,row2val3'],
uniqueAll: [],
arrayOfValuesOfFile:[]
}
for(var i=1;i<vm.allTextLines.length; i++){
let currentLinesValue = vm.allTextLines[i].split(',');
vm.uniqueAll.push(currentLinesValue);
for(var r =0; r < currentLinesValue.length; r++){
vm.arrayOfValuesOfFile.push(currentLinesValue[r]);
}
}
console.log('allTextLines', vm.allTextLines);
console.log('uniqueAll', vm.uniqueAll);
console.log('arrayOfValuesOfFile', vm.arrayOfValuesOfFile);
First you should transform you bidimensional array into a one-dimension array.
var allTogether = []; // Array with all your CSV (no matter from which file it came from)
for (var i = 0; vm.allTextLines.length; i++) {
allTogether.push(vm.allTextLines[i]); // Gets the CSV line an adds to a one-dimension array
}
// Now you can iterate over the one-dimension array
for (var i = 0; allTogether.length; i++) {
var csvFields = allTogether[i].split(',');
// Here goes your code that works with the CSV fields.
}
Related
I've come across writing a piece of code where I wanted to reference the 2D array d2_arr[][] in a loop like so.
for (var i=0; i<d2_arr[i].length; i++) {
//do something
}
Google Script compiler throws an error "cannot read length property from undefined". When I changed [i] for [1], it worked just fine. Could anyone please explain why this is wrong? And a related question: Can a 2D array have a different number of elements in a row? theoretically. An example would be:
[[1,2],[3,4,5],[6,7,8,9],[10,11]]
EDIT. Full code part.
var ids = [];
var j = 0;
for (var i=0; i<d2_arr[i].length; i++){
if (d2_arr[i][2]<=0.05){
ids[j]=d2_arr[i][0];
j++;
}
}
I understood the mistake. Thank you!
You typically need a nested for loop to traverse a 2-D array
var d2_arr = [[1,2],[3,4,5],[6,7,8,9],[10,11]]
for (var i=0; i<d2_arr.length; i++){
for (var j=0; j<d2_arr[i].length; j++){
console.log(d2_arr[i][j] + ' ')
}
}
It is perfectly fine for arrays to be "jagged" and contain uneven sized arrays in the main array.
Here is a fiddle http://jsfiddle.net/7Lr4542s/
Arrays in JS can be of any size and any type. You can combine number and strings in array.
var twoDArray = [[1], ["one", "two"], ["i", "ii", "iii"]];
for(var i = 0; i < twoDArray.length; i++) {
for(var j = 0; j < twoDArray[i].length; j++) {
print(twoDArray[i][j]);
}
}
var threeDArray = [[["1.1.1", "1.1.2"], ["1.2.1", "1.2.2"]], [["1.2.1", "1.2.2"], ["1.2.1", "1.2.2"]], [["2.1.1", "2.1.2"], ["2.2.1", "2.2.2"]], [["2.2.1", "2.2.2"], ["2.2.1", "2.2.2"]]];
for(var i = 0; i < threeDArray.length; i++) {
for(var j = 0; j < threeDArray[i].length; j++) {
for(var k = 0; k < threeDArray[i][j].length; k++) {
print(twoDArray[i][j][k]);
}
}
}
I have a Javascript array with multiple arrays inside. I was trying to loop through the array to return an aggregated array. So far I have done following with no luck:
var a = [[1,2,3],[4,5,56],[2,5,7]];
var x = [];
for ( var i = 0; i < a.length; i++) {
for ( var j = 0; j < a[i].length; j++) {
console.log(a[i][i] = a[i][j]+a[j][i]);
}
}
I am trying to obtain the following result:
console.log(a); // -> [7,12,66]
Any suggestions or pin points where I can look for examples of similar things would be appreciated.
assuming the elements of a has the same length, the following should work
var x=[];
for(var i=0; i<a[0].length; i++){
var s = 0;
for(var j=0; j<a.length; j++){
s += a[j][i];
}
x.push(s);
}
a[0].map(function(b,i){return a.reduce(function(c,d){return c+d[i];},0);})
// [7, 12, 66]
From dc2 to dc1, try this:
var a = [[1,2,3],[4,5,56],[2,5,7]];
var x = [];
for ( var i =0; i < a.length; i++){
for ( var j = 0; j < a[i].length; j++){
x[j] = x[j] || 0;
x[j] = x[j] + a[i][j];
}
}
This worked in testing, and doesn't error with different array lengths.
I have a table with numbers but they are stored as string so I am trying to use the function parseFloat to convert it into a table of ints. However, no matter how I do the for loops it gives me a blank table. I can parse the row and it will give me a single int. I can parse a single int as well but cant seem to parse a row or the table. here is what I have so far. This is just trying to convert one row. I tried two for loops for the entire table but that didn't work either. thanks.
var c =[];
var entries = $.parseJSON('<?php print(json_encode($try, true)); ?>');
for (var j = 0; j < 12; j++)
{
for (var i = 0; i < 7; i++)
{
c [j][i] = parseFloat(entries[j][i]);
}
}
alert(c);
here is entries json encodes [["-248","-163","-455","-1413","-1294","-1296","-1089"],["-172","-219","-1186","-1368","-1480","-1079","-845"],["-98","-198","-703","-996","-1100","-585","-616"],["-116","-241","-498","-642","-704","-354","-430"],["-137","-117","-264","-525","-533","-269","-476"],["-12","87","-257","-463","-551","-302","-535"],["170","61","-250","-472","-659","-220","-605"],["159","96","-234","-513","-617","-196","-710"],["185","117","-272","-521","-610","-258","-798"],["208","95","-234","-534","-696","-280","-854"],["192","151","-188","-641","-739","-279","-957"],["249","223","-235","-684","-763","-339","-978"]]
You have to initialize the second dimension of your array to also be an array. As it stands now, c[j] is just a single value so you can't do c[j][i] on it. There is also an error in your first for loop where you need to compare the value of j, not i. See this fixed code:
var c = [];
var entries = $.parseJSON('<?php print(json_encode($try, true)); ?>');
for (var j = 0; j < 12; j++)
{
c[j] = [];
for (var i = 0; i < 7; i++)
{
c [j][i] = parseFloat(entries[j][i]);
}
}
alert(c);
In your first loop for (var j = 0; i < 12; j++), you are using i for iteration but it is undefined and it should be j instead of i
var c =[];
var entries = $.parseJSON('<?php print(json_encode($try, true)); ?>');
for (var j = 0; j < entries.length ; j++)
{
c[j] = [];
for (var i = 0; i < entries[i].length ; i++)
{
c [j][i] = parseFloat(entries[j][i]);
}
}
This may be a fairly simple question but it's just not working for me no matter how many times I change the for loop around. So how would you loop through this array using a for loop in JavaScript?
var fielditems =[
[["News Tips"],["Opinions"],["MedMinutes"]],
[["Yes"],["No"],["Maybe"]],
[["How"],["Why"],["When"]]
];
This is what I have and it's not working. I used an alert to just test out the result but it's not even returning anything.
for(itemSet in fielditems){
var itemSetValues = fielditems[itemSet];
for(set in itemSetValues){
var itemValue = itemSetValues[set];
for(value in itemvalue){
alert(itemValue[value]);
}
}
}
What am I doing wrong?
Don't use for() with in for arrays. It's for object properties. Use the standard format instead.
Demo: http://jsfiddle.net/ThinkingStiff/EVWch/
Script:
var fielditems =[
[["News Tips"],["Opinions"],["MedMinutes"]],
[["Yes"],["No"],["Maybe"]],
[["How"],["Why"],["When"]]
];
for( var itemIndex = 0; itemIndex < fielditems.length; itemIndex++ ){
var itemSetValues = fielditems[itemIndex];
for(var setIndex = 0; setIndex < itemSetValues.length; setIndex++ ){
var itemValue = itemSetValues[setIndex];
for(var valueIndex = 0; valueIndex < itemValue.length; valueIndex++ ){
alert(itemValue[valueIndex]);
};
};
};
Firstly, console is your friend. You get error ReferenceError: itemvalue is not defined because javascript is case sensitive. Change itemvalue in the most nested loop to itemValue.
Secondly, if you want iterate thorugh an array, you should use for-loop instead for-in-loop
Don't use for-in loops on arrays
Don't use (running) variables without declaring them as local
for (var i=0; i<fielditems.length; i++) {
var itemSetValues = fielditems[i];
for (var j=0; j<itemSetValues.length; j++) {
var itemvalue = itemSetValues[j]; // notice the case
for (var k=0; k<itemvalue.length; k++) {
alert(itemvalue[k]);
}
}
}
for..in is for objects ({}), not for arrays ([]).
You need to use a standard for loop.
for(var i = 0, iLen = fielditems.length; i < iLen; i++){
var iItem = fielditems[i];
for(var j = 0, jLen = iItem.length; j < jLen; j++){
var jItem = iItem[j];
alert(jItem[0]); // you can also add another loop here, if this will have more elements
}
}
NOTE:
for(var i = 0, iLen = fielditems.length; i < iLen; i++)
is better than:
for(var i = 0; i < fielditems.length; i++)
because fielditems.length isn't requested each loop, just once at the start.
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