I am trying to simply print out a global array list of students that I have imported from a csv file. I've done enough troubleshooting to know that the data is being imported and read fine. The common answer seems to be that you don't require a "var" declaration for a global array but this wasn't working for me either.
Here is my declaration:
//Student array list from csv import
studentList = [];
//window.studentList = [];
This is where I initialize the array:
function processData(csv){
let allLines = csv.split(/\r\n|\n/);
for(let i = 0; i < allLines.length; i++)
{
let row = allLines[i].split(",");
let col = [];
for(let j = 0; j < row.length; j++)
{
col.push(row[j]);
}
if(col == " ") break;
studentList.push(col);
}
//when I alert the array element by element the data is being read from within this function
for(let i =0; i < studentList.length; i++)
{
alert(studentList[i]);
}
}
But if I was to use a get method to return the elements I would get an 'undefined' error
function getStudent(index) {
return studentList[index];
}
for(let i = 0; i < studentList.length; i++)
{
alert(getStudent[i]);
}
EDIT: Despite that solution being right, I still have the same issue when calling from another function. For example in the following I need to return the trip departure for each student which is undefined.
function getStudentsDeparture(i)
{
trip.departure = getStudent(i);
alert(trip.departure); //prints undefined
trip.destination = "123 Smith Rd, Maddingley VIC 3340";
console.log('dest is: ' + trip.destination + ' dept is: ' +
trip.departure);
}
The issue seems to be that you try to get an index from the function getStudent[i]. Try change that row to alert(getStudent(i)); with parenthesis.
EDIT
I tested with this code and it works fine for me
studentList = [];
studentList.push('student1');
function getStudent(index) {
return studentList[index];
}
function getStudentsDeparture(i) {
var student = getStudent(i);
alert(student);
}
getStudentsDeparture(0);
Related
I am importing excel files that contain customer orders like so
onFileChange(event: any) {
const inputFile: DataTransfer = <DataTransfer>(event.target);
const fileReader: FileReader = new FileReader();
fileReader.onload = (event: any) => {
const binaryString: string = event.target.result;
const workBook: XLSX.WorkBook = XLSX.read(binaryString, { type: 'binary', sheetStubs: true});
/* sheetstubs true supposedly shows empty cells but isn't */
console.log(typeof binaryString)
const workSheetName: string = workBook.SheetNames[0];
console.log(workSheetName)
const workSheet: XLSX.WorkSheet = workBook.Sheets[workSheetName];
this.data = <Array>(XLSX.utils.sheet_to_json(workSheet, { header: 1, blankrows: true }));
};
fileReader.readAsBinaryString(inputFile.files[0]);
console.log(this.data)
}
The way the excel files are imported an object of arrays where each array is a row of the excel sheet.
In the following code snippet, I am searching for items in a column to identify the column in an excel sheet that has the shoe brands requested by a customer in the code
for (var i=0; i<this.data.length; i++){
if (this.data[i].indexOf('Adidas') != -1) {
var manIndex = this.data[i].indexOf('Adidas')
for( var j = 0; j<this.data.length; j++){
this.manufactArray.push(this.data[j][manIndex])
}
}
else if (this.data[i].indexOf('Puma') != -1) {
var manIndex = this.data[i].indexOf('Puma')
for (var j=0; j<this.data.length; j++) {
this.manufactArray.push(this.data[j][manIndex])
}
}
else if (this.data[i].indexOf('Nike') != -1) {
var manIndex = this.data[i].indexOf('Nike')
for(var j = 0; j<this.data.length; j++){
this.manufactArray.push(this.data[j][manIndex])
}
}
}
}
this works in that it pushes all of the items in the relevant column into the array but it does so every time the conditions are met and as such the same column is pushed into the array a bunch of times as opposed to only pushing the column items once. Is there a way maybe using the % or other function so that the column is only pushed into the array one time? So if I had a customer sheet come in like this:
I would want the array to have [Nike, Adidas, Puma, Puma, Asics, Nike]
One way is to use a Set. You probably don't want to check if it is in the array before you add it, because then you may have O(n²) time complexity, which can be undesirable.
You can add it to a set, and return as a set, or if needed, return as an array:
const mySet = new Set();
mySet.add(123);
console.log([...mySet]);
mySet.add("hello world");
console.log([...mySet]);
mySet.add(123);
console.log([...mySet]);
I would have just used console.log(mySet) but for some reason StackOverflow can't print out its value (unlike Node.js or Chrome). But then it shows how to convert the set back to an array. You can also use Array.from(mySet).
So in your code, you probably have:
this.manufactSet = new Set();
and in the loop:
this.manufactSet.add(this.data[j][manIndex]);
and after the loop, you can set it back to an array:
this.manufactArray = [...this.manufactSet];
But I don't quite get your code:
for (var i=0; i<this.data.length; i++){
if (this.data[i].indexOf('Adidas') != -1) {
var manIndex = this.data[i].indexOf('Adidas')
for( var j = 0; j<this.data.length; j++){
this.manufactArray.push(this.data[j][manIndex])
}
Why when you found Adidas, then you push everything into the result?
Shouldn't you do:
for (var i=0; i<this.data.length; i++){
if (this.data[i].indexOf('Adidas') != -1) {
var manIndex = this.data[i].indexOf('Adidas')
this.manufactArray.push(this.data[i][manIndex])
?
Is this.data[i] a string that might have "Cool Adidas NMD hard to find"... and once you find the "location" of Adidas, why do you just push that character into the result?
Don't you want to push the whole string into the result?
for (var i=0; i<this.data.length; i++){
if (this.data[i].indexOf('Adidas') != -1) {
var manIndex = this.data[i].indexOf('Adidas')
this.manufactArray.push(this.data[i])
So after checking what data[i] is and what you would like to do, seems like this is what you want to do:
Note that you mentioned you actually want the manufacturer to appear more than once, like ["Adidas", "Adidas", "Nike", "Puma", "Nike"], so I won't use a set as the result below:
const someManufacturers = new Set(['Adidas', 'Puma', 'Nike']);
function getColumnNumber() {
for (var i = 0; i < this.data.length; i++) {
for (var j = 0; j < this.data[i].length; j++) {
if (someManufacturers.has(this.data[i][j])) return j;
}
}
}
var manufacturerColumnNumber = getColumnNumber();
for (var i = 0; i < this.data.length; i++) {
this.manufactArray.push(this.data[i][manufacturerColumnNumber]);
}
Actually, there is a better way to write it now in ES6:
const someManufacturers = new Set(['Adidas', 'Puma', 'Nike']);
function getColumnNumber() {
for (const row of this.data) {
for (let i = 0; i < row.length; i++) {
if (someManufacturers.has(row[i])) return i;
}
}
}
var manufacturerColumnNumber = getColumnNumber();
for (const row of this.data) {
this.manufactArray.push(row[manufacturerColumnNumber]);
}
I think I see what you mean by "pushing" every time instead of once. You mean if you see Adidas, you push the whole column values to the array, and the next row, you see Nike, and you push the whole column values to the array again. You could have just returned if you put that in a function. So once you see Adidas, then just push all values in that column to the array and return from the function.
I am trying to loop through an array of objects using Script Editor in Google Sheets. However, when I log the variable 'temp', it only returns the first letter of the first key of the first object in the array. I tried converting everything to a string using the TO_TEXT function, but it produced the same result.
I've looked through Google forums and can not find anything that pointed to a solution to this issue. Any help would be much appreciated.
The purpose of this project is to loop through a set data and identify if a particular action occurred that does not have a corresponding action. For instance, if a user viewed something, but did not also update that same thing, I want to push the object where the action was solely viewing into a separate array.
function onOpen() {
var ui = SpreadsheetApp.getUi();
ui.createMenu('Security Risk Audit - users')
.addItem('Perform user audit', 'getSheetData')
.addToUi();
}
var sheet = SpreadsheetApp.getActiveSheet();
var allSheetData = sheet.getDataRange().getValues();
var fileName = SpreadsheetApp.getActive().getName();
var headerRow = allSheetData[0];
var data = [];
var filteredData = [];
function getSheetData (){
for (var currentRow = 1; currentRow < allSheetData.length; currentRow++){
var obj = {};
for (var rowColumn = 0; rowColumn<headerRow.length; rowColumn++){
obj[headerRow[rowColumn]]=allSheetData[currentRow][rowColumn];
}
data.push(obj);
}
filterData();
}
function filterData() {
for (var i = 0; i < data.length; i++){
var temp = data[i].patientid[i];
Logger.log(temp);
for(var j = 0; j<data.length; j++) {
if(temp == data[j].patientid[j] && data[j].type[j] == "view"){
var temp2 = data[j].patientid[j];
} else {
return false;
}
for (var k = 0; k<data.length;k++){
if(temp2 == data[k].patientid[k] && data[k].type[k] != "view") {
return false;
}else{
filteredData.push(data[k]);
}
}
}
}
return filteredData;
}
I am having troubles figuring out the for condition for a javascript learning course I am doing.
I am not getting normal errors because I am doing it in the course, but the error I am receiving in the course is this...
Oops, try again. Careful: your second 'for' loop should stop when it reaches its current point in the string + myName.length.
These are the instructions:
First, you'll want to set your second loop's iterator to start at the first one, so it picks up where that one left off. If your first loop starts with
for(var i = 0; // rest of loop setup
your second should be something like
for(var j = i; // rest of loop setup
Second, think hard about when your loop should stop. Check the Hint if you get stuck!
Finally, in the body of your loop, have your program use the .push() method of hits. Just like strings and arrays have a .length method, arrays have a .push() method that adds the thing between parentheses to the end of the array. For example,
newArray = [];
newArray.push('hello');
newArray[0]; // equals 'hello'
This is my code
var text = "Hello, my name is Becky. What is your name?\
I repeat, my name is Becky. Can't you figure out that my\
name is Becky. Becky!!!!";
var myName = "Becky";
var hits = [];
for (i = 0; i < text.length; i++) {
if (text[i] === 'B') {
for (var j = i; i < myName.length; i++) {
hits.push();
}
}
}
I know the issue resides in this line:
for (var j = i; i < myName.length; i++) {
I just can't figure out exactly how I need to structure it.
UPDATE:
Final answer of question:
/*jshint multistr:true */
var text = "Hello, my name is Becky. What is your name?\
I repeat, my name is Becky. Can't you figure out that my\
name is Becky. Becky!!!!";
var myName = "Becky";
var hits = [];
for (i = 0; i < text.length; i++) {
if (text[i] === 'B') {
for (var j = i; j < (i + myName.length); j++) {
hits.push(myName);
}
}
}
if (hits === 0) {
console.log("Your name wasn't found!");
} else {
console.log(hits);
}
I'll give you the solution because you can learn more from the direct solution than from banging your head on that one.
var text = "Hello, my name is Becky. What is your name?\
I repeat, my name is Becky. Can't you figure out that my\
name is Becky. Becky!!!!";
var myName = "Becky";
var hits = [];
for (i = 0; i < text.length; i++) {
if (text[i] == 'B') {
var equal = true;
for (var j = 0; j < myName.length; j++) {
if (text[i + j] != myName[j]) {
equal = false;
break;
}
}
if(equal) hits.push(myName);
}
}
There may be other ways to reach this result. This is one of them.
Explaing what "push" does:
Arrays are lists of variables. You store a value in a variable like this:
var myNumber = 777;
var myName = "Nelson";
An array declaration looks like this:
var myNumbers = [];
then you put something inside of it, like this:
myNumbers.push(333);
myNumbers.push(555);
myNumbers.push(777);
then if you try: console.log(myNumbers), it will print: [333, 555, 777]
if you add another push:
myNumbers.push(999);
will add 999 to the list resulting in [333, 555, 777, 999]
Check this demo
got it ? take a look here to more detailed explanation:
http://www.hunlock.com/blogs/Mastering_Javascript_Arrays
Am not sure what you are trying to achieve,
Here is something may help
var text = "Hello, my name is Becky. What is your name?\
I repeat, my name is Becky. Can't you figure out that my\
name is Becky. Becky!!!!";
var myName = "Becky";
var hits = [];
for (i = 0; i < text.length; i++) {
if (text[i] == 'B') {
var res = '';
for (var j = i; j < i+myName.length; j++) {
res = res+text[j];
}
if(res == myName)
{
hits.push(myName);
}
}
}
console.log(hits);
Here is demo
I have surfed the problem but couldn't get any possible solution ..
Let's say i have a var like this
var data = [
{
'a':10,
'b':20,
'c':30
},
{
'a':1,
'b':2,
'c':3
},
{
'a':100,
'b':200,
'c':300
}];
Now , i need a multidimensional array like
var values = [[10,1,100], //a
[20,2,200], //b
[30,3,300]]; //c
What i have tried is
var values = [];
for(var key in data[0])
{
values.push([]); // this creates a multidimesional array for each key
for(var i=0;i<data.length;i++)
{
// how to push data[i][key] in the multi dimensional array
}
}
Note : data.length and number of keys keeps changing and i just want to be done using push() without any extra variables. Even i don't want to use extra for loops
If you guys found any duplicate here , just put the link as comment without downvote
Try this:
var result = new Array();
for(var i = 0; i < data.length; i++) {
var arr = new Array();
for(var key in data[i]) {
arr.push(data[i][key]);
}
result.push(arr);
}
also if you don't want the 'arr' variable just write directly to the result, but in my opinion code above is much more understandable:
for(var i = 0; i < data.length; i++) {
result.push(new Array());
for(var key in data[i]) {
result[i].push(data[i][key]);
}
}
Ok, based on your comment I have modified the the loop. Please check the solution and mark question as answered if it is what you need. Personally I don't understand why you prefer messy and hard to understand code instead of using additional variables, but that's totally different topic.
for(var i = 0; i < data.length; i++) {
for(var j = 0; j < Object.keys(data[0]).length; j++) {
result[j] = result[j] || new Array();
console.log('result[' + j + '][' + i + ']' + ' = ' + data[i][Object.keys(data[i])[j]])
result[j][i] = data[i][Object.keys(data[i])[j]];
}
}
Hello there am trying to save news tweets into three different array which are dynamically created.
am finding trouble when i want to get the text from each one of those array and make another request to twitter.
news_tweets("reuters","1652541",3);
function news_tweets(query, user_id,count) {
news_array = [];
$.getJSON("https://api.twitter.com/1/statuses/user_timeline.json?include_entities=true&include_rts=false&user_id=" + user_id + "&count="+count+
"&callback=?",
function (data) {
for (var i = 0; i < count; i++) {
var user = data[i].user.name;
var date = data[i].created_at;
var profile_img = data[i].user.profile_image_url;
var text = data[i].text;
var url = (data[i].entities.urls.length > 0 ? data[i].entities.urls[0].url : '');
news_array[i] = [{user:user,date:date,profile_img:profile_img,text:text,url:url}];
}
for (var i = 0; i < news_array.length; i++) {
for (var x=0; x<i.length; x++){
console.log(news_array[i][x].user);
}
}
});
}
It doesn't show anything on the console.log.
thanks for the help!!!!!
First, make sure that your count is smaller than the data array's length, otherwise this could lead to some undefined values:
for (var i = 0; i < count && i < data.length; i++) …
Then, why are you creating all those one-element-arrays in the news_array? Just use only objects.
This would solve your actual issue: You are looping wrong over those inner arrays. The correct code would be
for (var i = 0; i < news_array.length; i++) {
for (var x = 0; x < news_array[i].length; x++){
console.log(news_array[i][x].user);
}
}
Also, you should indent your code properly. You have some odd braces around, which don't make the code readable.
The problem is the x<i.length in the for loop near the end. i is a number, so it doesn't have a length. You probably meant x < news_array[i].length.
You may try the following:
Use the push method to append elements / data in your array new_array
Use only 1 loop for to display the user value on console
So your code will be something like this:
news_tweets("reuters","1652541",3);
function news_tweets(query, user_id,count) {
news_array = [];
$.getJSON("https://api.twitter.com/1/statuses/user_timeline.json?include_entities=true&include_rts=false&user_id=" + user_id + "&count="+count+
"&callback=?",
function (data) {
for (var i = 0; i < count; i++) {
var user = data[i].user.name;
var date = data[i].created_at;
var profile_img = data[i].user.profile_image_url;
var text = data[i].text;
var url = (data[i].entities.urls.length > 0 ? data[i].entities.urls[0].url : '');
// Pushing your elements in your array, 1 by 1
news_array.push({user:user,date:date,profile_img:profile_img,text:text,url:url});
}
// Here you only need 1 loop!
for (var i = 0; i < news_array.length; i++) {
console.log(news_array[i][x].user);
}
});
}
First thing is i would loop the first one till data.length rather than count because its an api and it "might" or "might not" return all the data. So it will be fool proof to loop till data.length
And your problem is with i.length
for (var i = 0; i < news_array.length; i++) {
console.log(news_array[i].user);
}
this should work. not sure why you had to loop through a loop.