JavaScript Array Accessing elements - javascript

I'm fairly new to Javascript, what I am trying to do is work out how to setup the correct array style for my form. What I want to be able to do is add each schedule to an array as a string and then be able to access the elements of that string(s) later for use such as sorting or searching for in the string. Currently its accessing each word as an index not a string first, the correct way to access an element within a string would be as myArray[0] = the string and then myArray[0][0] = the first element of that string and so on and so forth? I'd like to use vanilla Javascript as im still learning the fundamentals. Below is my code for how i am adding each schedule to the array, Im not sure where im going wrong, I think it has to do with the way its getting added to the global array. Thanks guys.
var myArr = new Array();
function addSchedule() {
var myPriority;
var date;
var endtime;
var mySubject;
if(document.getElementById('high').checked){
myPriority = document.getElementById('high').value;
}else if(document.getElementById('low').checked) {
myPriority = document.getElementById('low').value;
}
date = document.getElementById('Date').value;
endtime = document.getElementById('endtime').value;
mySubject = document.getElementById('Subject').value;
var priorityString = (myPriority)
var dateString = (date)
var subjectString = (mySubject)
// I think this needs to be a string some how but i dont know
var oneString = new Array(priorityString,dateString,endTimeString,subjectString)
myArr[myArr.length] = (oneString)

I think what you're actually trying to do is add objects to an array which represent each of the properties you're reading from your UI
var myArr = new Array();
function addSchedule() {
var myPriority;
var date;
var endtime;
var mySubject;
if(document.getElementById('high').checked){
myPriority = document.getElementById('high').value;
}else if(document.getElementById('low').checked) {
myPriority = document.getElementById('low').value;
}
date = document.getElementById('Date').value;
endtime = document.getElementById('endtime').value;
mySubject = document.getElementById('Subject').value;
// create an object
var myObj = {
priority: myPriority,
date : date,
endTime: endtime,
subject: mySubject
};
// add it to array
myArr.push(myObj);
}
Thereafter, if you wanted to read an object & it's properties from the array you could have
// for example:
var firstObjectPriority = myArr[0].priority;

Related

How to optimize this kind of code

How could i get the mark and mary by using searchstring and current_object? I have to use array_push for pushing new searchstring and current_object for create new output like mark and mary.
function get_suggestion_array_from_object(searchstring, current_object) {
var suggestion_array = [];
console.log(current_object);
}
var test_searchstring = 'Ma';
var test_current_object_string = '{"r":{"k":0,"y":0}}';
var test_current_object = JSON.parse(test_current_object_string);
get_suggestion_array_from_object(test_searchstring, test_current_object);
I'm not sure at all what it is you're asking but just a simple optimization would be this:
instead of writing a JSON string and then parsing it to an object, write the object immediatly:
var test_current_object_string = '{"r":{"k":0,"y":0}}';
var test_current_object = JSON.parse(test_current_object_string);
into:
var test_current_object = {r:{k:0, y:0}};

Javascript in Zapier to return multiple values for posting to Airtable database

I am trying to write some javascript in Zapier which will read two dates and then return an array of all dates between those dates in such a way that they can then be used to create multiple dated records in Airtable (a database). From the Zapier help it says that if you return an array of objects then the following steps will be processed for each.
I have managed to get code which returns the data I wan but it can't be correct because if I try to create the database records only one is created - with all the dates in (so it will only work if output to a text field - not a date). Here's my code attempt:
var fromDate = new Date(inputData.from);
var toDate = new Date(inputData.to);
var output =[];
var i = 1;
do {
var useDate = new String(fromDate.toISOString())
output.push(useDate);
console.log(fromDate);
fromDate.setDate(fromDate.getDate() + 1);
i++
}
while (fromDate <= toDate);
console.log(output);
return{output};
The subsequent step does see the output variable - but it is treated as one value as I said above.
Does anyone have any ideas?
Thanks Juan
That sorted it - or at least it did after removing the return - here is the working code:
var fromDate = new Date(inputData.from);
var toDate = new Date(inputData.to);
var output =[];
var i = 1;
do {
var useDate = new String(fromDate.toISOString())
var dateObject = {};
dateObject.date = useDate;
output.push({dateObject});
fromDate.setDate(fromDate.getDate() + 1);
i++
}
while (fromDate <= toDate);
It looks like you're returning an object, not an array of objects:
return{output};
Also, your do/while statement is creating an array of strings, not objects. In your do block, instead of pushing the useDate string to the output array, you should construct a simple object and push that to the output array.
So instead of pushing '2016-09-28T00:00:00.000Z' each time the loop runs, you should push something like {date: '2016-09-28T00:00:00.000Z'}.
Your do block should look something like this:
do {
var useDate = new String(fromDate.toISOString());
var dateObject = {};
dateObject.date = useDate;
output.push(dateObject);
fromDate.setDate(fromDate.getDate() + 1);
i++
}
This way, output will be an array of objects:
[
{
"date": "2016-09-28T00:00:00.000Z"
},
{
"date": "2016-09-29T00:00:00.000Z"
},
{
"date": "2016-09-30T00:00:00.000Z"
}
]

Javascript - create array between two date objects

Question
I am attempting to build an array between two JS objects. It appears that my objects are being created correctly, and in fact that the code below is running.
The unexpected behavior is that every object in my output array is transforming to match the last date that I looped through. i.e. if I loop, whatever my todate_dateobjis, I get an entire array of just that value.
I have to do some debugging wrt the actual start/end dates being correct, but I can handle that -- what I'm stymied by is the behavior described above.
I am very new to javascript. I imagine this is some issue with mutation? Any guidance would be appreciated.
I left the console logs in just because why take them out?
Code
function build_dateobjs_array(fromdate_dateobj, todate_dateobj) {
// return an array of dateojects from fromdate to todate
var current_date = fromdate_dateobj;
var return_array = []
while (current_date <= todate_dateobj) {
return_array[return_array.length] = current_date; // I have read that this is generally faster that arr.push()
var tomorrow = new Date(current_date.getTime() + 86400000);
console.log('tomorrow: ', tomorrow);
current_date.setTime(tomorrow);
console.log('current_date: ', current_date)
console.log("build_dateobjs_array : ", return_array);
};
return return_array;
};
Date objects are mutable. This line:
current_date.setTime(tomorrow);
...changes the state of the Date object that current_date refers to, which you never change.
So you're storing the same object repeatedly in return_array. Instead, make a copy of the Date:
return_array[return_array.length] = new Date(+current_date);
Also, it's probably best to change
var current_date = fromdate_dateobj;
to
var current_date = new Date(+fromdate_dateobj);
so you're not modifying the Date that was passed in.
Side note: There's no need for the round-trip to milliseconds, simply:
function build_dateobjs_array(fromdate_dateobj, todate_dateobj) {
// return an array of dateojects from fromdate to todate
var current_date = new Date(+fromdate_dateobj);
var return_array = [];
while (current_date <= todate_dateobj) {
return_array[return_array.length] = new Date(+current_date);
current_date.setDate(current_date.getDate() + 1);
};
return return_array;
}
(There's also no reason to put a ; at the end of a function declaration.)

javascript can't use input to grab an object property

So i've got this code below (all javascript). And I wish to grab the votecount for a game on user input
function Game(gamename,votes) {
this.gamename = gamename;
this.votes = votes;
};
var lol = new Game("League of Legends",1100);
var dota = new Game("DOTA 2",2100);
var ql = new Game("Quakelive",3100);
var csgo = new Game("Counter Strike: GO",4100);
function PostVotes(gnshort){
//string names - working
console.log(gnshort + 'name');
console.log(gnshort + 'votes')
var CalcVotes = function(gnshort){
var votecount = gnshort.votes;
console.log(votecount);
}
CalcVotes(gnshort);
//CalcVotes(lol); //works
};
PostVotes('lol');
I keep getting the error undefined when calling CalcVotes(gnshort). and I know it's not the function it's passing the lol as gnshort it's asif it's reading as a string instead of a variable or something. I've only been learning javascript for the past week so any advice would be helpful
PostVotes('lol'); will pass lol as a string ('lol' is equivalent to "lol"). What you need to do is simply pass the variable lol like
PostVotes(lol);
And it will return lol.votes, aka 1100.

Multi-dimensional array and timestamp

Here is the code :
var array = [];
$('.body-watch-logo').each(function () {
array[]['evendId'] = $(this).data('event');
array[]['timestamp'] = $(this).data('timestamp');
$now = new Date();
$outStr = now.getHours()+':'+now.getMinutes();
alert($outStr);
if(array[]['timestamp'] == $outStr) {
alert('Tring Tring Tring');
//do something here
}
$i++;
});
.body-watch-logo has several events in it with attributes eventId and startTime. So I want to store this information in array. Then compare the startTime which has only Hour and minute with current-time. If they are equal give an alert. Does anyone have an idea how to do this? Use Ajax may be. Please suggest.
You incremented i, but never initialized it or used it as your array index. But you don't need to do either, since .each() passes the index as an argument to the iteration function. See
http://api.jquery.com/jQuery.each/
The elements of the array are better implemented as objects, not sub-arrays.
var array = [];
$('.body-watch-logo').each(function (i) {
array[i] = { event: $(this).data('event'),
timestamp: $(this).data('timestamp')
};
$now = new Date();
$outStr = now.getHours()+':'+now.getMinutes();
alert($outStr);
if(array[i].timestamp == $outStr) {
alert('Tring Tring Tring');
//do something here
}
});

Categories

Resources