Load csv data to an array - javascript

I have a csv file containing entries as follows:
a,10
b,20
c,30
d,40
In JavaScript, I want to assign this csv file to a variable lets say x as follow:
x = [
['a',10],
['b',20],
['c',30],
['d',40]
]
Can someone tell me how i can do this.

If your CSV is really that simple, you just need two splits and a loop:
var rows = "a,10\nb,20\nc,30\nd,40".split('\n');
var x = [];
for(var i=0; i<rows.length; i++) {
x.push(rows.split(','));
}
A shorter version:
var x = "a,10\nb,20\nc,30\nd,40".split('\n').map(function(val) {
return val.split(',');
});

Related

How to fix the Error : TypeError : Cannot read properly 'setValues' of undefined google app script. How to implement it to my the code?

I made files with table. On those table there is some datas that are changing according to each files. So I created a file where there is a table that sum all of the others tables that are in others files.
First i made my code that sum tables of two files :
function juneFunction() {
var sheet_origin1=SpreadsheetApp
.openById("ID1")
.getSheetByName("Calcul/Machine");
var sheet_origin2=SpreadsheetApp
.openById("ID2")
.getSheetByName("Calcul/Machine");
var sheet_destination=SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
//define range as a string in A1 notation
var range1="BU4:CF71"
var values1=sheet_origin1.getRange(range1).getValues();
var values2=sheet_origin2.getRange(range1).getValues();
var destinationrange=sheet_destination.getRange("C3:N70");
//Here you sum the values of equivalent cells from different sheets
for(var i=0; i<values1.length;i++)
{
for(var j=0; j<values1[0].length;j++)
{
sum=values1[i][j]+values2[i][j];
destinationrange.getCell(i+1,j+1).setValue(sum);
}
}
}
This code is working perfectly.
But my goal is to sum 26 tables of 26 files.
So I tried to do it with 3 files, here is the code :
function juneFunction() {
var sheet_origin1=SpreadsheetApp
.openById("ID1")
.getSheetByName("Calcul/Machine");
var sheet_origin2=SpreadsheetApp
.openById("ID2")
.getSheetByName("Calcul/Machine");
var sheet_origin3=SpreadsheetApp
.openById("ID3")
.getSheetByName("Calcul/Machine");
var sheet_destination=SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
//define range as a string in A1 notation
var range1="BU4:CF71"
var values1=sheet_origin1.getRange(range1).getValues();
var values2=sheet_origin2.getRange(range1).getValues();
var values3=sheet_origin3.getRange(range1).getValues();
var destinationrange=sheet_destination.getRange("C3:N70");
//Here you sum the values of equivalent cells from different sheets
for(var i=0; i<values1.length;i++)
{
for(var j=0; j<values1[0].length;j++)
{
for(var k=0; k<values1[0].length;k++){
sum=values1[i][j][k]+values2[i][j][k]+values3[i][j][k];
destinationrange.getCell[[i+1,j+1,k+1]].setValues(sum);
}
}
}
}
Here I have this error : TypeError : Cannot read properly 'setValues' of undefined. This error happen here :
destinationrange.getCell[[i+1,j+1,k+1]].setValues(sum);
I think that the error is coming from the .getCell but i dont know why ...
Range.getCell() takes two arguments: the row offset and the column offset. You are handing it just one argument: an array of three numbers.
You should not be using Range.getCell() in the first place. Instead, use Array.map() to get the sheets, Array.forEach() to iterate over them, and finally Range.setValues() to write all results in one go, like this:
function sumRangeAcrossManySpreadsheets() {
const spreadSheetIds = ['id1', 'id2', 'id3',];
const sheetName = 'Calcul/Machine';
const rangeA1 = 'BU4:CF71';
const targetRange = SpreadsheetApp.getActiveSheet().getRange('C3');
const sheets = spreadSheetIds.map(id => SpreadsheetApp.openById(id).getSheetByName(sheetName));
const result = [];
sheets.forEach((sheet, sheetIndex) => {
if (!sheet) {
throw new Error(`There is no sheet ${sheetName} in spreadsheet ID '${spreadSheetIds[sheetIndex]}'.`);
}
const values = sheet.getRange(rangeA1).getValues();
values.forEach((row, rowIndex) => row.forEach((value, columnIndex) => {
if (!result[rowIndex]) {
result[rowIndex] = new Array(row.length).fill(0);
}
result[rowIndex][columnIndex] += Number(value) || 0;
}));
});
targetRange.offset(0, 0, result.length, result[0].length).setValues(result);
}

How can I create an array from an input string using JavaScript?

Currently I have a PHP page returning some values. The data is something like this:
08-30-2018, in
08-29-2018, out
08-28-2018, in
08-27-2018, in
How can I create a custom array in Javascript with the values above to be similar as this array below:
var system = [
['08-30-2018', 'in'],
['08-29-2018', 'out'],
['08-28-2018', 'in'],
['08-27-2018', 'in']
];
I have tried array.push, but it does not create an array like above.
What should I do? Can you help me? Thank you!
You can use multi-dimensional arrays in JavaScript
var system = [];
var output = "08-30-2018, in\n08-29-2018, out\n08-28-2018, in\n08-27-2018, in";
var items = output.split("\n");
for(i=0; i<items.length; i++){
var data = items[i].split(",");
var item = [];
item.push(data[0].trim());
item.push(data[1].trim());
system.push(item);
}
console.log(system);
You could also parse this kind of input using regular expressions:
const input = '08-30-2018, in\n08-29-2018, out\n08-28-2018, in\n08-27-2018, in';
const regex = /(\d{2}-\d{2}-\d{4}), (in|out)/g;
let system = [];
let match;
while ((match = regex.exec(input)) !== null) {
system.push([match[1], match[2]]);
}

How to change JSON into string

i got a words array in JSON form like:
var words = [];
words.push({word:"I",x:50,y:50});
and i want it to store into a txt file which user can download from the website.
...
var data = JSON.stringify(words);
var file = new Blob([data],{type:'plain/text'});
...
however the output file is like this:
{"word":"Peaceful","x":40,"y":65,"lyric":"lyric"}
but i want it only print out the word "peaceful", i tried to use
var data = JSON.stringify(words.word);
but the output shows undefined.
words is an array, so you have to index it to access the object that you pushed onto it:
var data = JSON.stringify(words[0].word);
If I understand you correctly.
var myWords = [];
(for var i = 0; i < words.length; i++) {
var word = words[i].word;
myWords.push(word);
}
myWords.join(' '); // or myWords.join('\n');

jQuery/JavaScript - Converting CSV to Array

I am trying to to convert a CSV file into a javascript array.
Here is my code:
var segments = {
'Segment_1':'inves_cast',
'Segment_2':'foreged_prod',
'Segment_3':'air_prod',
'Segment_5':'worldwide',
'Segment_6':'structurals'
};
var divisions = {
'Division_1':'structurals',
'Division_2':'airfoils',
'Division_3':'wyman',
'Division_4':'energy',
'Division_5':'fasteners',
'Division_6':'struc_comp',
'Division_7':'mech_hard',
'Division_8':'engine_prod',
'Division_9':'corp',
'Division_10':'aero',
'Division_11':'timet',
'Division_12':'',
'Division_13':'spec_metals',
};
var csv = $.get('/path/to/locations.csv');
console.log(csv);
var locationArray = transformLocationData(csv);
function transformLocationData(obj) {
var lineArray = [];
if(obj && obj.data) {
var text = (data.responseText);
lines = text.split('\n');
for(var line in lines) {
var lineTokens = line.split(',');
lineArray = [
lineTokens[0],
lineTokens[1],
lineTokens[3],
lineTokens[4],
lineTokens[5],
lineTokens[6],
lineTokens[11],
lineTokens[12],
lineTokens[13],
lineTokens[14],
lineTokens[15],
segments['Segment_' + lineTokens[8]],
divisions['Division_' + lineTokens[9]]
];
}
}
console.log(lineArray);
}
So what I am trying to do is us AJAX to get the csv file and then split the "responseText" first by line and Second loop through those lines and split it up by commas and then create an array based on those line numbers.
Here is a picture of the data I am getting back from the AJAX call:
With the last console log ( console.log(lineArray); ) it returns an empty array or really it just returns the data the is in var lineArray = []; which is empty if I populate it with data var lineArray = ["Lexus", "Audi", "BMW"]; It will return that array.
Here is a plunker with all the code: https://plnkr.co/edit/CoZGfr6S9R5LDqR1drzq
I know I am doing something wrong but cant seem to get it. I'm not familiar with doing this kind of thing so any help would be greatly appreciated.
You are replacing lineArray with a new array every time, and you're only logging the array at the end of the loop. Perhaps the CSV has an empty line at the end.
If you're wanting an array of arrays, do this instead:
var lineArray = [];
if(obj && obj.data) {
var text = (data.responseText);
lines = text.split('\n');
for(line in lines) {
var lineTokens = line.split(',');
lineArray.push([
lineTokens[0],
lineTokens[1],
lineTokens[3],
lineTokens[4],
lineTokens[5],
lineTokens[6],
lineTokens[11],
lineTokens[12],
lineTokens[13],
lineTokens[14],
lineTokens[15],
segments['Segment_' + lineTokens[8]],
divisions['Division_' + lineTokens[9]]
]);
}
}
console.log(lineArray);
Update:
In addition, you're not handling the results from the Ajax request properly. This line:
var csv = $.get('/path/to/locations.csv');
...does not return the CSV. Rather, it returns a Promise (sort of...). So you cannot parse csv like that. Rather, wait for the results. Change your code to:
$.get('/path/to/locations.csv').then(function (csv) {
var locationArray = transformLocationData(csv);
}, function (err) {
// Handle errors
});
As #vlaz alluded to, you'll also want to change your loop from for..in to a regular for loop:
for (var i = 0; i < lines.length; i++) {
var line = lines[i];
// ...
}

converting plain text into json

Suppose I have a text file that I want to convert into json file. Precisely, I want to convert each line $line to "$line":"someid" . Is there a proper way to do that using bash script langage or javascript.
For example
I want to
convert
text into
json
would output
{{"I want to":"1"},{"convert","2"},{"text into":"3"},{"json":"4"}}
You can't do your expected output like that because you will produce a syntax error, but you can put multiple objects in an array instead. Something like this:
HTML
<div id="id">
I want to
convert
text into
json
</div>
JS
var textArr = document.querySelector('#id').innerHTML.split('\n');
function produceJSON(textArr) {
var arr = [];
// we loop from 1 to 1 less than the length because
// the first two elements are empty due to the way the split worked
for (var i = 1, l = text.length - 1; i < l; i++) {
var obj = {};
obj[text[i]] = i;
arr.push(obj);
}
return JSON.stringify(arr);
}
var json = produceJSON(textArr);
DEMO

Categories