I am trying to build out an object that contains the NFL's 2012 schedule. I found a CSV of it online and can parse through it ok except for when I am trying to add games to each week. When I console log the schedule after the code executes each week only get one game (the last one) instead of the 16 (or so, depending on byes) they should have.
Note: Normally I put my prototypes in a source file instead of here but for clarity I included them.
BONUS: I'll post the object when it is complete. : D
Here's my code:
String.prototype.trim = function() {
return this.replace(/^\s+|\s+$/g,"");
}
String.prototype.capitalize = function() {
return this.substr(0, 1).toUpperCase() + this.substr(1);
}
Object.prototype.getKeys = function(obj){
var keys = [];
for(var key in obj){
keys.push(key);
}
return keys;
}
Array.prototype.contains = function(obj) {
var i = this.length;
while (i--) {
if (this[i] == obj) {
return true;
}
}
return false;
}
var AppController = {};
//create a schedule object
AppController.Schedule = {};
var schedule = AppController.Schedule;
var scheduleArray = nflschedule.split(":::");
//set a game count so we can give each game an id
var gameCount = -1;
for(var i=0; i<scheduleArray.length; i++) {
gameCount++;
//filter out first line
if (i>0) {
//get a game
var thisGameItems = scheduleArray[i].split(",");
//game date
var gameDate = thisGameItems[0];
//week number
var colonSplitPattern = new RegExp("^[^:]+(?=:)");
var weekNumPattern=new RegExp("\Week(.*)");
var weekNum = "Week" + thisGameItems[2].match(colonSplitPattern).toString().match(weekNumPattern)[1].trim();
//get teams and game day
var homeTeam = thisGameItems[thisGameItems.length-3].trim();
var visitingTeam = thisGameItems[thisGameItems.length-2].trim();
var weekDay = thisGameItems[thisGameItems.length-1].trim().capitalize();
//check Schedule and see if we have this weekNum as key, if not add it
var gameWeeks = schedule.getKeys();
if (gameWeeks.contains(weekNum) == false) {
schedule[weekNum] = {};
}
var thisWeeksGames = schedule[weekNum];
//add games to the game week
thisWeeksGames[gameCount] = {
GameDate: gameDate,
GameWeek: weekNum,
HomeTeam: homeTeam,
VisitingTeam: visitingTeam,
GameDay: weekDay,
HomeTeamScore : "",
VistingTeamScore : ""
}
}
}
console.log(schedule);
Related
Plugin: eonasdan/Bootstrap 3 Datepicker
Explaination:
I want to write an application that user can select 5 different hours for each day. so i created an array and add each day (without duplicate), for example user select 31/12/2017 and 30/12/2017 , now i want to give they this ability to select only 5 different hour for each day that selected.
Tried Code:
var limit = 5;
var i = 0;
var dateArray = new Object();
$('#ss').click(function() {
if ($('#datetimepicker1 input').val().length > 0) {
var date = $('#datetimepicker1 input').val();
var getDate = date.split(' ');
var unqdate = getDate[0];
var unqtime = getDate[1];
if ($.inArray(unqdate, dateArray) == -1) {
dateArray[unqdate] = unqtime
}
}
console.log(dateArray);
});
JSFiddle
(For testing, select a date, then click on save button, then check console)
Goal:
var dateArray = {
"31-12-2017": [{
"time": "14:00"
}, {
"time": "17:15"
}],
"30-12-2017": [{
"time": "13:00"
}, {
"time": "12:15"
}]
}
Problem:
I couldn't figured out how can i add another time to each day. it's my first time i work with array and object like this.
I want to prevent duplicate entry and only five different hour per day.
Somehow I'm in learning.
There is some problem with your JS Code:
var limit = 5;
var i = 0;
var dateArray = new Object();
$('#ss').click(function() {
if ($('#datetimepicker1 input').val().length > 0) {
var date = $('#datetimepicker1 input').val();
var getDate = date.split(' ');
var unqdate = getDate[0];
var unqtime = getDate[1];
if ($.inArray(unqdate, dateArray) == -1) {
if(dateArray[unqdate] && dateArray[unqdate].length < limit) {
if(!dateArray[unqdate].find((ele) =>ele.time === unqtime)){
dateArray[unqdate].push({"time": unqtime})
}
} else {
dateArray[unqdate] = [{"time": unqtime}]
}
}
}
console.log(dateArray);
});
Note included logic for time split. You can use split by : and take the first 2 element of array.
I have created JSON response for your requirement.
Result :: JSON.stringify(parentObject)
Code is as below.
$(document).ready(function() {
$('#datetimepicker1').datetimepicker({
stepping: 30,
sideBySide: true,
showTodayButton: true,
format: 'DD-MM-YYYY HH:mm:ss',
});
// my code
var limit = 5;
var i = 0;
var parentObject = new Object();
var parentArray = [];
var dateAndTimeObject;
function isDateSelectedExists(date) {
for (var i = 0; i < parentArray.length; i++) {
var obj = parentArray[i];
if (obj["date"] === date) {
return i;
}
}
return -1;
}
$('#ss').click(function() {
if ($('#datetimepicker1 input').val().length > 0) {
var date = $('#datetimepicker1 input').val();
var getDate = date.split(' ');
var unqdate = getDate[0];
var unqtime = getDate[1];
var tempIndex = isDateSelectedExists(unqdate);
console.log("tempIndex :: " + tempIndex);
if (tempIndex == -1) {
console.log("date doesn't exists");
dateAndTimeObject = new Object();
dateAndTimeObject["date"] = unqdate;
var timeArray = [];
timeArray.push(unqtime);
dateAndTimeObject["time"] = timeArray;
parentArray.push(dateAndTimeObject);
parentObject["res"] = parentArray;
} else {
console.log("date exists");
dateAndTimeObject = parentArray[tempIndex];
var timeArray = dateAndTimeObject["time"];
if(timeArray.length<5) timeArray.push(unqtime);
dateAndTimeObject["time"] = timeArray;
}
console.log("final res :: " + JSON.stringify(parentObject));
}
});});
I have this google spreadsheet script that pulls in json formatted book data. I have no problem displaying book title and author, but he "offerData" object can contain a different amount of elements (prices from sellers) depending on the book. Right now I created a loop and am storing the offerData values like so:
price[i] = offerdata.offers[i]["price"];
condition[i] = offerdata.offers[i]["condition"];
seller[i] = offerdata.offers[i]["seller"]["displayName"];
and am returning the data like this:
var resultRow = [[title, specstag, price[0], condition[0], seller[0], price[1], condition[1], seller[1], price[2], condition[2], seller[2]]];
Obviously this only returns 3 sellers with price, condition, seller info. The issue is that a book doesn't always have 3 sellers, it can be anywhere from 1 to 10 or so.
My question is how can I return all offerData (price/condition/seller) here? :
var resultRow = [[title, specstag, price[0], condition[0], seller[0], price[1], condition[1], seller[1], price[2], condition[2], seller[2]]];
--
function getBookDetails(isbn) {
// Query the book database by ISBN code.
if (isbn !== "") {
var url = "https://api.bol.com/catalog/v4/search/?apikey=myapi6&offers=all&format=json&q=" + isbn;
var response = UrlFetchApp.fetch(url);
var results = JSON.parse(response);
if (results.totalResultSize) {
// There'll be only 1 book per ISBN
var book = results.products[0];
// get Title and Authors
var title = (results.products[0]["title"]);
var specstag = (results.products[0]["specsTag"]);
var offerdata = results.products[0]["offerData"];
if (typeof offerdata.offers !== 'undefined' && offerdata.offers.length > 0) {
var arrayLength = offerdata.offers.length;
var price = [];
var condition = [];
var seller = [];
for (var i = 0; i < arrayLength; i++) {
price[i] = offerdata.offers[i]["price"];
condition[i] = offerdata.offers[i]["condition"];
seller[i] = offerdata.offers[i]["seller"]["displayName"];
}
}
}
var resultRow = [[title, specstag, price[0], condition[0], seller[0], price[1], condition[1], seller[1], price[2], condition[2], seller[2]]];
return resultRow;
}
}
the answer
var resultRow = [];
resultRow[0] = [];
resultRow[0][0]=title;
resultRow[0][1]=specstag;
for (var i = 0; i < arrayLength; i=1+3) {
resultRow[0][3*i+2]=price[i];
resultRow[0][3*i+3]=condition[i];
resultRow[0][3*i+4]=seller[i];
}
how you should think about it is to see the index of the elements in the array and then find relation between i and the index you want
var resultRow = [
[
title, //[0][0]
specstag, //[0][1]
price[0], //[0][2]
condition[0], //[0][3]
seller[0], //[0][4]
price[1], //[0][5]
condition[1], //[0][6]
seller[1], //[0][7]
price[2], //[0][8]
condition[2], //[0][9]
seller[2]//[0][10]
]
];
You might be looking for something like this;
var data = { title: null,
spcstag: null,
pcs: [],
};
offerData.offers.forEach( p => { var pcsData = {};
!!data.title || data.title = p.title;
!!data.specstag || data.specstag = p.specstag;
pcsData.price = p.price;
pcsData.condition = p.condition;
pcsData.seller = p.seller;
data.pcs.push(pcsData);
});
I have a javascript object as below
var mydata=[
{"Club":"Blackburn","EventNo":1,"Pnts":3,"CumPnts":0},
{"Club":"Blackburn","EventNo":2,"Pnts":1,"CumPnts":0},
{"Club":"Blackburn","EventNo":3,"Pnts":4,"CumPnts":0},
{"Club":"Preston","EventNo":1,"Pnts":2,"CumPnts":0},
{"Club":"Preston","EventNo":2,"Pnts":4,"CumPnts":0},
{"Club":"Preston","EventNo":3,"Pnts":2,"CumPnts":0},]
I want to update the object so that CumPnts contains a running points total for each Club as below
{"Club":"Blackburn","EventNo":1,"Pnts":3,"CumPnts":3},
{"Club":"Blackburn","EventNo":2,"Pnts":1,"CumPnts":4},
{"Club":"Blackburn","EventNo":3,"Pnts":4,"CumPnts":8},
{"Club":"Preston","EventNo":1,"Pnts":2,"CumPnts":2},
{"Club":"Preston","EventNo":2,"Pnts":4,"CumPnts":6},
{"Club":"Preston","EventNo":3,"Pnts":1,"CumPnts":7},]
Any help would be much appreciated
Here is a function that loops through the list and updates it after it's been added. But I suspect that the events come in one at a time so there could be another function that can look the cumPtns obj and take from that. Here is for the current list.
var cumData = {};
var mydata=[
{"Club":"Blackburn","EventNo":1,"Pnts":3,"CumPnts":0},
{"Club":"Blackburn","EventNo":2,"Pnts":1,"CumPnts":0},
{"Club":"Blackburn","EventNo":3,"Pnts":4,"CumPnts":0},
{"Club":"Preston","EventNo":1,"Pnts":2,"CumPnts":0},
{"Club":"Preston","EventNo":2,"Pnts":4,"CumPnts":0},
{"Club":"Preston","EventNo":3,"Pnts":2,"CumPnts":0}];
function updateMyData() {
for (var i = 0; i < mydata.length; i++) {
var item = mydata[i];
if(cumData[item.Club] == undefined) {
cumData[item.Club] = {};
cumData[item.Club] = item.Pnts;
} else {
cumData[item.Club] = cumData[item.Club] + item.Pnts;
}
mydata[i].CumPnts = cumData[item.Club];
};
console.log(mydata);
//if you want to return it you can have this line below. Otherwise the object is updated so you'll probably want to do something with it once it's updated. Call back maybe?
return mydata;
}
updateMyData();
The first time it encounters a team it adds it to an array and so does with the corresponding cumPnts, so we can keep track of whether we checked a team earlier or not.
var tmArr = [];
var cumArr = [];
for(var i = 0; i < mydata.length; i++) {
var elm = mydata[i];
var club = elm.Club;
var points = elm.Pnts;
var idx = tmArr.indexOf(club);
if(idx > -1) {
cumArr[idx] += points;
elm.CumPnts = cumArr[idx];
}
else {
elm.CumPnts = points;
tmArr[tmArr.length] = club;
cumArr[cumArr.length] = points;
}
}
jsfiddle DEMO
I want to create a array containing objects, and I'm using Parse to query all the data.
However, the for loop which loops over the results doesn't does that in the correct order but randomly loops over the data. If I log i each iteration, the logs show different results every time.
Here is my code:
for (var i = 0; i < results.length; i++)
{
Parse.Cloud.useMasterKey();
// retrieve params
var objectid = results[i];
var self = request.params.userid;
// start query
var Payment = Parse.Object.extend("Payments");
var query = new Parse.Query(Payment);
query.get(objectid, {
success: function (payment) {
// get all the correct variables
var from_user_id = payment.get("from_user_id");
var to_user_id = payment.get("to_user_id");
var amount = payment.get("amount");
var createdAt = payment.updatedAt;
var note = payment.get("note");
var img = payment.get("photo");
var location = payment.get("location");
var status = payment.get("status");
var fromquery = new Parse.Query(Parse.User);
fromquery.get(from_user_id, {
success: function(userObject) {
var fromusername = userObject.get("name");
var currency = userObject.get("currency");
var toquery = new Parse.Query(Parse.User);
toquery.get(to_user_id, {
success: function(touser)
{
var tousername = touser.get("name");
if(tousername !== null || tousername !== "")
{
sendArray(tousername);
}
},
error: function(touser, error)
{
var tousername = to_user_id;
if(tousername !== null || tousername !== "")
{
sendArray(tousername);
}
}
});
function sendArray(tousername) {
var array = new Array();
// create the time and date
var day = createdAt.getDate();
var year = createdAt.getFullYear();
var month = createdAt.getMonth();
var hour = createdAt.getHours();
var minutes = createdAt.getMinutes();
// create the timestamp
var time = "" + hour + ":" + minutes;
var date = "" + day + " " + month + " " + year;
var associativeArray = {};
if(self == from_user_id)
{
fromusername = "self";
}
if(self == to_user_id)
{
tousername = "self";
}
associativeArray["from"] = fromusername;
associativeArray["to"] = tousername;
associativeArray["amount"] = amount;
associativeArray["currency"] = currency;
associativeArray["date"] = date;
associativeArray["time"] = time;
associativeArray["status"] = status;
if(note == "" || note == null)
{
associativeArray["note"] = null;
}
else
{
associativeArray["note"] = note;
}
if(img == "" || img == null)
{
associativeArray["img"] = null;
}
else
{
associativeArray["img"] = img;
}
if(location == "" || location == null)
{
associativeArray["location"] = null;
}
else
{
associativeArray["location"] = location;
}
array[i] = associativeArray;
if((i + 1) == results.length)
{
response.success(array);
}
},
error: function(userObject, error)
{
response.error(106);
}
});
},
error: function(payment, error) {
response.error(125);
}
});
}
But the i var is always set to seven, so the associative arrays are appended at array[7] instead of the correct i (like 1,2,3,4,5)
The reason that this is so important is because I want to order the payment chronologically (which I have done in the query providing the results).
What can I do to solve this issue?
Success is a callback that happens at a later point in time. So what happens is, the for loop runs 7 times and calls parse 7 times. Then after it has run each of parse success calls will be executed, they look at i which is now at 7.
A simple way to fix this is to wrap the whole thing in an immediate function and create a new closure for i. Something like this
for(var i = 0; i < results.length; i++){
function(iClosure) {
//rest of code goes here, replace i's with iClosure
}(i);
}
Now what will happen is that each success function will have access to it's own iClosure variable and they will be set to the value of i at the point they were created in the loop.
I'm a beginner in java script a trying a little program that parse data from a text file. In order to create a filter on a particular date i have made a function to get the date from and to that the user have enter. And the date a have to compare if it is in the range is in the text file, this date also i got it. But now i don't want to re-write the function "getAllFilesFromFolder" found in the code below, this function must be executed in all case but if i click on the button filter by by date it must read on the files with the date in range given by the user. Can someone give me an explanation on how to do it. i have tried the code below.
function getdate(){
var dateStart = new Date($('#dateStart').val()).getTime();
var dateEnd = new Date($('#dateEnd').val()).getTime();
//if(!testDate){var testDate = new Date(2014, 05, 02).getTime();}
var testDate = new Date(2014, 05, 02).getTime();
if (dateStart <= testDate && testDate <= dateEnd) {
alert('IN');
//Here filter the files with the date
}else{
alert('OUT');
//Here no new to read and parse the file beacause it is out of range
}
}
//Parse folder and file to get the required files
function getAllFilesFromFolder(folder){
//Parsing the given folder the result which is return is kept in an array
var test = fse.readdirSync(folder);
//Going through the array
for(var n=0; test[n]; n++){
var stats = fs.lstatSync(folder+"\\"+test[n]);
if(stats && stats.isDirectory()){
getAllFilesFromFolder(folder+"\\"+test[n]);
var path = folder+"\\"+test[n]+"<br />";
}else{
var path = folder+"\\"+test[n];
//Regex on the file to be taken
var pattern = /^(PM)[0-9]{5}[_](xam)[_](pmbok5th)[_](pmp)[_](v92)(.txt)$/;
var parent = folder+"\\";
var file = test[n];
var load = pattern.test(file);
//Split on file to get the "id user"
identifiant = file.split('_');
//Test the regex on file name "PM*_xam_pmbok5th_pmp_v92.txt"
if(load == true){
var read = fse.readFileSync(path, 'utf8');
var suspendDate = read.lastIndexOf('xam/');
var wantedDate = read.slice(suspendDate);
info = wantedDate.split('/');
var suspendData = read.lastIndexOf('/DB');
var suspendData = wantedDate.lastIndexOf('/DB');
var wantedData = wantedDate.slice(suspendData);
var db_response = wantedData.split(".");
var all_response = db_response[0].split(":");
if(typeof(info[2]) != "undefined" && all_response != "undefined"){
var response = all_response[1].split("|");
//Parsing the array response to find the "id" here id of the question and the "ans" here answer of the question "R" or "W"
for(var p = 0; p < response.length; p++){
//Test if result exist we increment if not it is generate with the function initResp
if(typeof(response[p]) != "undefined"){
var id = response[p].slice(0,6);
var ans = response[p].slice(-1);
if (question[id]) {
question[id][ans] += 1;
} else {
var results = initResp(ans);
question[id] = results;
};
} else {
}
}
} else {
//$("#results1").append("<strong>La session est vide</strong><br>");
}
i++;
}
}
}
};
I found a solution to my problem. See the code below for more information
function rangeDate(testDate){
var dateStart = new Date($('#dateStart').val()).getTime();
var dateEnd = new Date($('#dateEnd').val()).getTime();
if (dateStart <= testDate && testDate <= dateEnd) {
date = true;
return date;
}else{
date = false;
return date;
}
}
function getAllFilesFromFolder(folder)/*, useDate*/{
//Parsing the given folder the result which is return is kept in an array
var test = fse.readdirSync(folder);
//Going through the array
for(var n=0; test[n]; n++){
var stats = fs.lstatSync(folder+"\\"+test[n]);
if(stats && stats.isDirectory()){
getAllFilesFromFolder(folder+"\\"+test[n]);
var path = folder+"\\"+test[n]+"<br />";
}else{
var path = folder+"\\"+test[n];
//Regex on the file to be taken
var pattern = /^(PM)[0-9]{5}[_](xam)[_](pmbok5th)[_](pmp)[_](v92)(.txt)$/;
var parent = folder+"\\";
var file = test[n];
var load = pattern.test(file);
//Split on file to get the "id user"
identifiant = file.split('_');
//Test the regex on file name "PM*_xam_pmbok5th_pmp_v92.txt"
if(load == true){
var read = fse.readFileSync(path, 'utf8');
var suspendDate = read.lastIndexOf('xam/');
var wantedDate = read.slice(suspendDate);
var info = wantedDate.split('/');
testDate = new Date(info[4]).getTime();
rangeDate(testDate);
if(date == true){
var suspendData = read.lastIndexOf('/DB');
var suspendData = wantedDate.lastIndexOf('/DB');
var wantedData = wantedDate.slice(suspendData);
var db_response = wantedData.split(".");
var all_response = db_response[0].split(":");
if(typeof(info[2]) != "undefined" && all_response != "undefined"){
var response = all_response[1].split("|");
//Parsing the array response to find the "id" here id of the question and the "ans" here answer of the question "R" or "W"
for(var p = 0; p < response.length; p++){
//Test if result exist we increment if not it is generate with the function initResp
if(typeof(response[p]) != "undefined"){
var id = response[p].slice(0,6);
var ans = response[p].slice(-1);
if (question[id]) {
question[id][ans] += 1;
} else {
var results = initResp(ans);
question[id] = results;
};
} else {
}
}
} else {
//$("#results1").append("<strong>La session est vide</strong><br>");
}
i++;
}else{
}
}
}
}
};