How to add value from one array to another array - javascript

edit #3
in the interest of getting better help (THANK YOU for the patience) i want to combine these two scripts:
SCRIPT 1:
//get csv file and set up array
d3.csv('../mapdata/mapdatatest.csv', function (csv) {
var rid = [],
lat = [],
lon = [],
pinclr = [],
name = [],
str = [],
citystzip = [],
phone = [],
lastinspturl = [],
lastinspctdt = [];
csv.map(function (d) {
rid.push(d.rid).toString();
lat.push(d.lat).toString();
lon.push(d.lon).toString();
pinclr.push(d.pinclr).toString();
name.push(d.name).toString();
str.push(d.str).toString();
citystzip.push(d.citystzip).toString();
phone.push(d.phone).toString();
lastinspturl.push(d.lastinspturl).toString();
lastinspctdt.push(d.lastinspctdt).toString();
for (i = 0; i < rid.length; i++) {
var points = ('"' + lat[i] + "," + lon[i] + '"');
}
});
});
SCRIPT 2:
deCarta.Core.Configuration.clientName = Config.clientName;
deCarta.Core.Configuration.clientPassword = Config.clientPassword;
var center = new deCarta.Core.Position(Config.position);
var pinOverlay = new deCarta.Core.MapOverlay({
name: "Pins"
});
window.map = new deCarta.Core.Map({
id: "mapContainer",
autoResize: true,
zoom: 11,
center: center,
onReady: function (map) {
map.addLayer(pinOverlay);
postPins();
}
});
function postPins() {
var points = {
"points": [
//i have typed in these values for testing purposes only
"47.15211, -97.570039",
"48.625045, -101.375369",
"48.39679, -101.052669"]
};
for (var i = 0; i < points.points.length;) {
pos = new deCarta.Core.Position(points.points[i]);
pin = pin = new deCarta.Core.Pin({
position: center.clone(),
text: 'pin: ' + (points.points[i]),
position: pos
// imageSrc: 'img/pin.png'
});
pinOverlay.addObject(pin);
i++;
}
var view = new deCarta.Core.BoundingBox(points.points);
var centerAndZoom = view.getIdealCenterAndZoom(window.map);
map.zoomTo(centerAndZoom.zoom);
map.centerOn(centerAndZoom.center);
}
THE RESULT I AM TRYING TO ACHIEVE:
instead of using typed in values as i'm doing in SCRIPT 2 -- i want those values to be fed in from SCRIPT 1.
so
var points = {
"points": [
//i have typed in these values for testing purposes only
"47.15211, -97.570039",
"48.625045, -101.375369",
"48.39679, -101.052669"]
};
needs to be
var points = {
"points": [
THE "point" VALUES FROM THE SCRIPT 1 loop]
};
i get the concept, can't seem to get the syntax right...tried all the suggestions, the push();, read a lot of articles, samples...i needed this 10 hours ago, any assistance will be greatly appreciated. i'd vote you up if i had enough rep yet :) thank you, thank you, thank you.

I'm having a hard time understanding your questions. Does this help at all:
var points = {
"points": [
"47.15211, -97.570039",
"48.625045, -101.375369",
"48.39679, -101.052669"
]
};
console.log(points.points);
var array = points.points;
var array_len = array.length;
for(var i = 0; i < array_len; ++i)
{
var str = array[i];
console.log(str);
}
--output:--
[ '47.15211, -97.570039',
'48.625045, -101.375369',
'48.39679, -101.052669' ]
47.15211, -97.570039
48.625045, -101.375369
48.39679, -101.052669
======
i built on another page:
That is troublesome. Are you aware that the web is stateless? That means that once a user leaves a page, no data is saved on the user's computer. There are some ways around that: you can save small bits of information in cookies, or a page can send the data to a server side script, and then the server side script can save the data in a file or a database.
On the other hand, if by "on another page" you mean another javascript file, then start simpler. Combine both javascript files into one file and get that to work, e.g.:
func1(a, b) = {
....
return results;
}
func2(x, y, z) = {
info = func1(x, y) + z
//do something with info
}
Then it's a just a matter of putting func1 and func2 into separate files and including both of them in an html page:
<script type='text/javascript' src='js2.js'></script>
<script type='text/javascript' src='js1.js'></script>
Just make sure you get the order right: if function in js1.js calls a function defined in js2.js, then js2.js needs to be included first.
====
html.html
<html>
<head>
<title>Test</title>
<script type='text/javascript' src='js2.js'></script>
<script type='text/javascript' src='js.js'></script>
<style type='text/css'>
.colorText {
color: blue;
}
.surprise {
background: red;
}
</style>
</head>
<body>
<div id="show_results" class="colorText">Hello world</div>
</body>
</html>
js.js
function do_stuff(x, y, z) {
//send two of this function's arguments to another function
//defined in another script:
var results = do_other_stuff(x, y);
return results + z;
}
//This function will execute once the html page loads:
window.onload = function() {
var my_results = do_stuff(10, 20, 30);
alert("Inserting results in <div>");
//The following div won't exist until after the page loads:
var div = document.getElementById('show_results');
div.innerHTML = my_results;
}
If the window.onload thing is too confusing, just get rid of it and use alert()'s to show the results (or any other info you are interested in).
js2.js
function do_other_stuff(x, y) {
return x+y;
}
Now, if you want to pass just one thing to the do_other_stuff() function, e.g. your object (things with braces around them are called 'objects'), you can rewrite your scripts like this:
js.js
function do_stuff() {
var points = {
"points": [
"47.15211, -97.570039",
"48.625045, -101.375369",
"48.39679, -101.052669" ]
};
do_other_stuff(points);
}
do_stuff();
Then rewrite do_other_stuff() to look like this:
js2.js
function do_other_stuff(points_obj) {
//do stuff with points_obj, e.g.
alert( points_obj.points[0] );
}
In this example, the scripts aren't operating on any of the html elements, so there is no need to wait for the page to load.
====
See if the following comments help:
1) This loop:
for (i = 0; i < rid.length; i++) {
var points = ('"' + lat[i] + "," + lon[i] + '"');
}
is equivalent to:
var points = '"' + lat[rid.length] + "," + lon[rid.length] + '"';
2) The thing you are doing with the quotes there is really ugly. If you are just trying to turn some numbers into a string, you can do this:
var point = lat[i] + ", " + lon[i];
js can't add a number and a string together, so js makes the assumption that you are trying to create a string, and js converts the number to a string then adds the strings together. Check this out:
var str = 3 + ', ' + 2;
var arr = [str];
console.log(arr);
--output:--
[ '3, 2' ]
3) You probably want to do something like this:
var points = []
for (i = 0; i < rid.length; i++) {
points.push( lat[i] + ", " + lon[i] );
}
4) Then to pass the points array to your deCarta stuff, you can do this:
var points = []
for (i = 0; i < rid.length; i++) {
points.push( lat[i] + ", " + lon[i] );
}
do_stuff(points);
And then you would define do_stuff() like this:
function do_stuff(the_points) {
//Do all your deCarta stuff here
window.map = new deCarta.Core.Map({
id: "mapContainer",
autoResize: true,
zoom: 11,
center: center,
onReady: function (map) {
map.addLayer(pinOverlay);
postPins();
}
});
function postPins() {
console.log(the_points); //You have access to the points array
obj = {"points": the_points};
=======
1) When you call a function, js lines up the function call with the function definition:
do_stuff(10, 20, 30) <----function call
function do_stuff( x, y, z) {...} <---function definition
Then javascript does these assignments:
var x = 10;
var y = 20;
var z = 30;
2) Then inside the function, you use the variables x, y, and z to refer to those values.
3) In the code I posted, the function call and function definition look like this:
do_stuff(points)
function do_stuff(the_points) {...}
So js does this assignment:
var the_points = points;
And points is just some array like ['10, 20', '100, 200'], so that assignment is equivalent to:
var the_points = ['10, 20', '100, 200']
And inside the function you use the_points to refer to the array.

You can use something like this to run through each pair in the array:
var points = [ "47.15211, -97.570039", "48.625045, -101.375369", "48.39679, -101.052669"];
points.forEach(function (point) {
point = point.match(/^"([0-9\.]+)\s*,\s*([0-9\.]+)"$/);
console.log('"' + point[0] + '", "' + point[1] + '"');
});
Or something like this if you're wanting to put them in their own arrays:
var points = [ "47.15211, -97.570039", "48.625045, -101.375369", "48.39679, -101.052669"],
lat = [], lon = [];
points.forEach(function (point) {
point = point.match(/^"([0-9\.]+)\s*,\s*([0-9\.]+)"$/);
lat.push(point[0]);
lon.push(point[1]);
});
lat.forEach(function (lat, id) {
console.log('"' + lat + '", "' + lon[id] + '"');
});
Or even:
lon.forEach(function (lon, id) {
console.log('"' + lat[id] + '", "' + lon + '"');
});
Also, someone commented on here and said that I shouldn't be using split for this when you're joining it back together. If you're not looking to have them separated like this, you can always use:
points.points = points.points.map(function (point) {
return point.replace(/^"([0-9\.]+)\s*,\s*([0-9\.]+)"$/, '"$1", "$2"');
});

Maybe this will work but I don't know what your variables rid, lat and long are. Maybe you could post it. To see the variable in Chrome or Firefox you can do:
console.log(JSON.stringify(rid);
Press F12 to see the console.
var points={};
points.points=[];
for (i = 0; i < rid.length; i++) {
points.points.push('"' + rid[i].lat + "," + rid[i].lon + '"');
}

Related

How to dynamically create new objects in a loop

I'm following a JS course and I was wondering if it was possible to create new variables in loops?
My example:
JavaScript
var films = {
init: function (titre, annee, real) {
this.titre = titre;
this.annee = annee;
this.real = real;
},
decrire: function () {
var description = this.titre + "(" + this.annee + ")" + ", réalisé par " + this.real;
return description;
}
};
for (var i = 0; i < 4; i++) {
var film = Object.create(films);
film = prompt("Film:");
annee = prompt("année");
real = prompt("real");
}
films.forEach(function (film) {
console.log(decrire());
}
I would like to create new objects at each turn of the loop and ask people for titles, years, and realisators, finally print it in the console.
But I get something like this for my last line of code:
Uncaught SyntaxError: missing ) after argument list
And my webpage doesn't ask me to put a new movie =/ I don't know how to figure this out.
Where could I find some documentation about this?
Missing ) to close forEach function. Should be
films.forEach(function (film){
console.log(decrire());
});
EDIT: Your code contains several other errors too. Sorry for ignoring.
Yes, you can create new variables in loops.
I have fixed your code like you probably wanted it to work. See code comments.
// It's recommened to use Capitalized name for a "class" like here.
// This is NOT very good Javascript, but it works.
var Film = {
init: function (titre, annee, real) {
this.titre = titre;
this.annee = annee;
this.real = real;
},
decrire: function () {
var description = this.titre + "(" + this.annee + ")" + ", réalisé par " + this.real;
return description;
}
};
// Initial array of films
var films = [];
for (var i = 0; i < 4; i++) {
var film = Object.create(Film);
// Save user inputs
var titre = prompt("Film:");
var annee = prompt("année");
var real = prompt("real");
// Run init function for created
film.init(titre, annee, real);
// Save it to array of films
films.push(film);
}
films.forEach(function (film) {
// Run decrire() of each film in the array
console.log(film.decrire());
});
you're not closing your forEach:
films.forEach( function (film){
console.log( decrire() );
} );
EDIT: admitted, it only answer the error, not the rest of the question

Accessing Stored Object

I have an object "Driver" defined at the beginning of my script as such:
function Driver(draw, name) {
this.draw = draw;
this.name = name;
}
I'm using this bit of JQuery to create new drivers:
var main = function () {
// add driver to table
$('#button').click(function ( ) {
var name = $('input[name=name]').val();
var draw = $('input[name=draw]').val();
var draw2 = "#"+draw;
var name2 = "driver"+draw
console.log(draw2);
console.log(name2);
if($(name2).text().length > 0){
alert("That number has already been selected");}
else{$(name2).text(name);
var name2 = new Driver(draw, name);}
});
That part is working great. However, when I try later on to access those drivers, the console returns that it is undefined:
$('.print').click(function ( ) {
for(var i=1; i<60; i++){
var driverList = "driver"+i;
if($(driverList.draw>0)){
console.log(driverList);
console.log(driverList.name);
}
If you're interested, I've uploaded the entire project I'm working on to this site:
http://precisioncomputerservices.com/slideways/index.html
Basically, the bottom bit of code is just to try to see if I'm accessing the drivers in the correct manner (which, I'm obviously not). Once I know how to access them, I'm going to save them to a file to be used on a different page.
Also a problem is the If Statement in the last bit of code. I'm trying to get it to print only drivers that have actually been inputed into the form. I have a space for 60 drivers, but not all of them will be used, and the ones that are used won't be consecutive.
Thanks for helping out the new guy.
You can't use a variable to refer to a variable as you have done.
In your case one option is to use an key/value based object like
var drivers = {};
var main = function () {
// add driver to table
$('#button').click(function () {
var name = $('input[name=name]').val();
var draw = $('input[name=draw]').val();
var draw2 = "#" + draw;
var name2 = "driver" + draw
console.log(draw2);
console.log(name2);
if ($(name2).text().length > 0) {
alert("That number has already been selected");
} else {
$(name2).text(name);
drivers[name2] = new Driver(draw, name);
}
});
$('.print').click(function () {
for (var i = 1; i < 60; i++) {
var name2 = "driver" + i;
var driver = drivers[name2];
if (driver.draw > 0) {
console.log(driver);
console.log(driver.name);
}

Getting array from text

I have been experimenting with this code http://mounirmesselmeni.github.io/2012/11/20/javascript-csv/ to get data from a text file. (Working demo here: http://mounirmesselmeni.github.io/html-fileapi/).
It works well for reading files, but I am stumped about how to get the data into an array. It seems as though it is reading everything into the "lines" array, but I can't work out how to use it.
I tried modifying it like this:
function processData(csv) {
var allTextLines = csv.split(/\r\n|\n/);
var lines = [];
var myArray = [];
while (allTextLines.length) {
lines.push(allTextLines.shift().split(','));
myArray.push(allTextLines.shift().split(',')); //put data into myArray
}
function myFunction() { //display myArray in "demo"
var index;
for (index = 0; index < myArray.length; index++) {
text += myArray[index];
}
document.getElementById("demo").innerHTML = text;
}
but that didn't work. I know I am missing something simple here, but this has me stumped.
Currently you modify the array twice:
lines.push(allTextLines.shift().split(',')); // shift modifies the array
myArray.push(allTextLines.shift().split(',')); //gets the shifted array
You might want to try putting this in temp variable:
var line = allTextLines.shift().split(',');
lines.push(line);
myArray.push(line);
Try
csv.split(/\r\n|\n|,/).map(function(value, index) {
demo.innerHTML += "\n" + value.trim()
});
var csv = 'Year,Make,Model,Description,Price'
+ '1997,Ford,E350,"ac, abs, moon",3000.00'
+ '1999,Chevy,"Venture ""Extended Edition""","",4900.00'
+ '1999,Chevy,"Venture ""Extended Edition, Very Large""",,5000.00'
+ '1996,Jeep,Grand Cherokee,"MUST SELL!'
+ 'air, moon roof, loaded",4799.00',
demo = document.getElementById("demo");
csv.split(/\r\n|\n|,/).map(function(value, index) {
demo.innerHTML += "\n" + value.trim()
})
<div id="demo"></div>

TypeError: Cannot read property "0" from undefined - Javascript

I am trying to run the following code and I am getting the following error:
TypeError: Cannot read property "0" from undefined. (line 111)
The line in question would be:
perCampaignRows.push([STRATEGISTS[i][1],
and here's the full code.
var perCampaignRows = [];
for (var i = 0; i < STRATEGISTS.length; i++) {
var accountIterator = MccApp.accounts()
.withCondition("ManagerCustomerId = '" + STRATEGISTS[i][0] + "'")
.get();
var mccAccount = AdWordsApp.currentAccount();
while (accountIterator.hasNext()) {
var account = accountIterator.next();
MccApp.select(account);
Logger.log("Checking " + account.getName() + " - CID: " + account.getCustomerId());
var campaignIterator = AdWordsApp.campaigns()
.withCondition("Status = ENABLED")
.get();
var activeCampaigns = campaignIterator.totalNumEntities();
if (activeCampaigns === 0) {
Logger.log("No Active Campaigns");
perCampaignRows.push([
STRATEGISTS[i][1],
STRATEGISTS[i][2],
account.getCustomerId(),
account.getName(),
activeCampaigns,
'',
'',
'',
'',
'',
'',
'',
'',
'',
'',
]);
}
else {
Logger.log(activeCampaigns + " Active Campaigns");
}
while (campaignIterator.hasNext()) {
var campaign = campaignIterator.next();
Logger.log("Campaign: " + campaign.getName());
var mobileBid = checkPlatform(campaign);
var isRotatingEvenly = checkAdRotation(campaign);
var sitelinkData = checkSitelinks (campaign);
var isUsingMobileAds = checkAds(campaign);
var callExtData = checkCallExtensions(campaign);
var isUsingAdSchedule = checkAdSchedules(campaign);
var isSomewhatLimitedByBudget = checkBudgetLimitations(campaign);
if (isUsingAdSchedule && isSomewhatLimitedByBudget) {
var warnAboutBudgetAndSchedule = "TRUE";
}
else {
var warnAboutBudgetAndSchedule = "FALSE";
}
Logger.log(perCampaignRows);
perCampaignRows.push([
STRATEGISTS[i][1],
STRATEGISTS[i][2],
account.getCustomerId(),
account.getName(),
activeCampaigns,
campaign.getName(),
mobileBid,
isRotatingEvenly,
sitelinkData[0],
sitelinkData[1],
sitelinkData[2],
isUsingMobileAds,
callExtData[0],
callExtData[1],
warnAboutBudgetAndSchedule
]);
}
}
}
I don't really get why it's not working, considering I am declaring the array at the beginning. It's also worth noting that I did declare STRATEGISTS as a multi-dimensional array, like this:
var STRATEGISTS = [
['346-963-8912','Brizza','Arcadio'],
['885-612-1069','Doria','Arcadio'],
['922-596-2785','Edgar','Arcadio']
]
Any ideas?
EDIT
As per request I added:
Logger.log(STRATEGISTS.length);
Logger.log(STRATEGISTS);
The first one logged 51, and the second one logged the variable as expected.
Thanks,
So thanks to Guffa I realized that even though I had broken the push statement into different lines, it was treated as one. I had thought the problem was with my .push implementation, but rather it was a problem with one of the variables being pushed.
It turns out I had missed a return on
var callExtData = checkCallExtensions(campaign);
and so callExtData was empty, hence undefined.
Thanks!

Return Top Track Spotify API

I am trying to create a helper file that will return the top track(s) of any artist's related artists. All I want to do use 1 artist URI to surface their related artists' name, popularity, and top track. And I want to separate out the top track functionality into a separate file that I can call whenever.
But, I can't seem to figure out how to properly return the top track of the related artists.
In my "get-toptrack.js" file:
require([
'$api/models',
'$api/toplists#Toplist'
], function(models, Toplist) {
'use strict';
var doGetTopTrack = function(uri, num) {
var artistURI = uri;
var artist = models.Artist.fromURI(artistURI);
var artistTopList = Toplist.forArtist(artist);
artistTopList.tracks.snapshot().done(function(snapshot){
snapshot.loadAll('name').done(function(tracks) {
var i, num_toptracks;
num_toptracks = num;
for(i = 0; i < num_toptracks; i++){
console.log("top track: " + tracks[i].name);
// WHERE DO I RETURN THE TOP TRACKS??
}
});
});
};
exports.doGetTopTrack = doGetTopTrack;
});
In my "artist.js" file":
require([
'$api/models',
'scripts/get-toptrack'
], function(models, getTopTrack) {
'use strict';
var showRelated = function() {
var artist_properties = ['name', 'popularity','related', 'uri'];
models.Artist
.fromURI('spotify:artist:11FY888Qctoy6YueCpFkXT')
.load(artist_properties)
.done(function(artist){
artist.related.snapshot().done(function(snapshot){
snapshot.loadAll('name').done(function(artists) {
for(var i = 0; i < artists.length; i++){
var u, p, n, t, listItem;
// store artist details
p = artists[i].popularity;
n = artists[i].name;
u = artists[i].uri;
// am I missing something here?
t = getTopTrack.doGetTopTrack(u, 1);
listItem = document.createElement("li");
listItem.innerHTML = "<strong>Name</strong>: " + n.decodeForText() + " | <strong>Popularity: </strong> " + p + " | <strong>Top Track: </strong>" + t;
// undefined name
$('#artistsContainer').append(listItem);
}
});
});
});
};
exports.showArtists = showArtists;
});
And in the 'main.js' file, I call the artists function to begin.
require([
'$api/models',
'scripts/artist'
], function(models, initArtist) {
'use strict';
initArtist.showRelated();
});
can't comment on the multiple .js files as I haven't yet refactored my app into multiple files.
As far as returning goes, you're working in an asynchronous application, so you can't. You have to use a callback, or a Spotify Promise might make your api more congruous with Spotify's. Look at the documentation for Promise.each().
Here is an implementation of the callback method. Changed a few things to make it easier for me to test. Made life a bit easier to pass the artist in instead. Also, there is no guarantee of the order they will come out since the second artist's toplist could come back faster than the first. You'll need to add more code if you want to keep order.
function doGetTopTrack(artist, num, callback) {
var artistTopList = Toplist.forArtist(artist);
artistTopList.tracks.snapshot(0,num).done(function (snapshot) { //only get the number of tracks we need
snapshot.loadAll('name').done(function (tracks) {
var i, num_toptracks;
num_toptracks = num; //this probably should be minimum of num and tracks.length
for (i = 0; i < num_toptracks; i++) {
callback(artist, tracks[i]);
}
});
});
};
function showRelated() {
var artist_properties = ['name', 'popularity', 'related', 'uri'];
models.Artist
.fromURI('spotify:artist:11FY888Qctoy6YueCpFkXT')
.load(artist_properties)
.done(function (artist) {
artist.related.snapshot().done(function (snapshot) {
snapshot.loadAll('name').done(function (artists) {
for (var i = 0; i < artists.length; i++) {
// am I missing something here?
doGetTopTrack(artists[i], 1, function (artist, toptrack) {
console.log("top track: " + toptrack.name);
var p = artist.popularity;
var n = artist.name;
var u = artist.uri;
//listItem = document.createElement("li");
console.log("<strong>Name</strong>: " + n.decodeForText() + " | <strong>Popularity: </strong> " + p + " | <strong>Top Track: </strong>" + toptrack.name);
//// undefined name
//$('#artistsContainer').append(listItem);
});
}
});
});
});
};
showRelated();

Categories

Resources