Hello I want to extract elements from both arrays with the same url .How can i loop these two arrays and get their content, because it gives me undefined for the news_url and i think it outputs twice the items in the console.
function geo(news_array,user_tweets){
console.log(news_array,user_tweets);
for (var x=0; x<user_tweets.length; x++) {
var user = user_tweets[x].user;
var date = user_tweets[x].date;
var profile_img = user_tweets[x].profile_img;
var text = user_tweets[x].text;
var url=user_tweets[x].url;
second(user,date,profile_img,text,url);
}
function second(user,date,profile_img,text,url){
for (var i = 0; i < news_array.length; i++) {
var news_user = news_array[i].news_user;
var news_date = news_array[i].news_date;
var news_profile_img = news_array[i].news_profile_img;
var news_text = news_array[i].news_text;
var news_url=news_array[i].url;
if (url==news_array[i].news_url) {
geocode(user,date,profile_img,text,url,news_user,news_date,news_profile_img,news_text,news_url);
}
}
}
function geocode(user,date,profile_img,text,url,news_user,news_date,news_profile_img,news_text,news_url) {
console.log(url,news_url);
}
}
The problem is
in news_tweets function, you add news_url to news_array. So you should call
news_array[i].news_url
in second function.
I modify your code as
news_url: (item.entities.urls.length > 0)?item.entities.urls[0].url : '' in news_tweets function
add close brace } for geo function and remove } from last
add new_array parameter to second function like second(user, date, profile_img, text, url,news_array);
Modify code can be tested in http://jsfiddle.net/rhjJb/7/
You have to declare some variables before the first for loop, so that they can be accessed in the scope of the second function. Try to replace your first for loop with the following code:
var user, date, profile_img, text, url;
for (var x=0; x<user_tweets.length; x++){
user = user_tweets[x].user;
date = user_tweets[x].date;
profile_img = user_tweets[x].profile_img;
text = user_tweets[x].text;
url=user_tweets[x].url;
second(user,date,profile_img,text,url);
}
Moreover, in the if of your second function, news_array[i].news_url isn't defined. Use if (url == news_url) instead.
Related
I'm passing a string which looks something like: "John.Doe.100.Newbie-David.Miller.250.Veteran-" to the SplitDatabase function which splits the string appropriately and assigns the values to the UserDataEntry object. The UserDataEntry object is then pushed in to the global UserData array which is supposed to store all the user data.
For some reason though, the UserData.push(UserDataEntry) part seems to be overwriting previous data in the UserData array. The alert in the 1st loop shows the correct data as it loops, but alert in the second loop at the bottom just shows the last record over and over again.
I'm not sure why this is?
var UserData = [];
function SplitDatabase(result) {
var RawUsers = result.split('-');
var UserDataEntry = {};
for (var i = 0; i < (RawUsers.length - 1); i++) {
var tempUserData = RawUsers[i].split('.');
for (var x = 0; x < (tempUserData.length); x++) {
switch (x) {
case 0:
UserDataEntry.firstname = tempUserData[x];
break;
case 1:
UserDataEntry.lastname = tempUserData[x];
break;
case 2:
UserDataEntry.points = tempUserData[x];
break;
case 3:
UserDataEntry.rank = tempUserData[x];
UserData.push(UserDataEntry);
alert(UserData[i].firstname);
break;
}
}
}
for (var i = 0; i < (UserData.length); i++) {
alert(UserData[i].firstname);
}
}
Calling push will not copy your object, because JavaScript Objects are passed by reference: you're pushing the same Object as every array entry.
You can fix this easily by moving the var UserDataEntry = {}; inside the loop body, so that a new object is created each loop iteration:
for (var x = 0; x < (tempUserData.length); x++) {
var UserDataEntry = {};
Put your line var UserDataEntry = {} inside the for loop.
Right now, you only have one object, and you're setting each part of the array to that object. You overwrite the members in your loop.
If you create a new object inside the loop, you'll add all new members in to the array.
Meet with a really weird javascript problem. See my codes below:
function initBadScripts(controlArray) {
var scriptsLine = prompt("Please enter the bad scripts", "debug");
if (scriptsLine != null) {
var pattern = /;/;
var nameList = scriptsLine.split(pattern);
alert(nameList+" "+nameList.length);
for(var counter = 0; counter < nameList.length; counter++){
controlArray[counter][0]=true;
controlArray[counter][1]= new RegExp(nameList[counter],"g");
alert(controlArray[counter][0]);
}
}
alert("wtf!");
}
var controlArray = [[]];
initBadScripts(controlArray);
I defined a function, and call that function. A 2-dimensional array called 'controlArray' is defined with no value. Basically, the function check the user's input and use regular expression to make a 'namelist'. For example, if the user type in
ExampleOne;ExampleTwo
The function will create an array called 'nameList'
nameList=[ExampleOne,ExampleTwo];
Then I want to make a dynamical initialization of the 2-dimensional array called 'controlArray', according to the length of nameList. However this only works fine the nameList'length is 1. If it exceeds one (the user type in 'ExampleOne;ExampleTwo'), the ExampleTwo does not go into the array, and the
alert("wtf");
doesn't run at all. This seems that there is already an error before it. Any comments?
JavaScript doesn't have a true 2-dimensional array. Rather, you're putting a second array inside the first array. Change it to this:
...
for(var counter = 0; counter < nameList.length; counter++){
controlArray[counter] = [true, new RegExp(nameList[counter],"g")];
...
Yes or you declare your variable like that:
var controlArray = [[],[]];
or
var controlArray = new Array(2);
for (var i = 0; i < 2; i++) {
controlArray[i] = new Array(2);
}
i'm new to javascript and jquery and was wondering if someone could let me in on why this isn't working correctly.
i have a drop-down box that a user selects a value from, then "Processes." When processed the value of the drop-down as well as a textbox is stored in an array. I want the user to be able to then basically store the same drop-down selection and textbox data in the array again but now in a new value pair.
First store would be
TestArray[0][0] = "Textbox Value"
If "Processed" again, it would be
TestArray[1][0] = "Textbox Value"
that way I can parse through later and figure how many times the user "Processed" the drop-down selection;
var oneClickReport = $("#reportName").val();
if(oneClickReport == "Sample Report One"){
var arrayOneCount = reportOneArray.length;
var totalHouseholds = 0;
$("#reportChecks span:visible").each(function(){
if($(this).find(':checkbox').prop('checked')){
var HHName = $(this).text();
reportOneArray.push(HHName);
arrayTest[arrayOneCount][totalHouseholds] = HHName;
}
totalHouseholds += 1;
});
for(i = 0; i < arrayOneCount; i+=1){
alert(arrayTest[0][i]);
}
}
But when trying to "Process" for the second time, I receive the error of;
SCRIPT5007: Unable to set property '0' of undefined or null reference
on line;
arrayTest[arrayOneCount][totalHouseholds] = HHName;
You need to initialize your array. I'm not sure what exactly you want to do but you need an array like this
var arrayTest = []
And you will need to initialize subsequent value like
arrayTest[1] = []
Then you can access your array
arrayTest[1][0] = []
I made an example for you
var oneClickReport = $("#reportName").val();
var arrayTest = [] # You may need to put this elsewhere
if(oneClickReport == "Sample Report One"){
var arrayOneCount = reportOneArray.length;
var totalHouseholds = 0;
$("#reportChecks span:visible").each(function(){
if($(this).find(':checkbox').prop('checked')){
var HHName = $(this).text();
reportOneArray.push(HHName);
if(!arrayTest[arrayOneCount]){ arrayTest[arrayOneCount] = []; }
arrayTest[arrayOneCount][totalHouseholds] = HHName;
}
totalHouseholds += 1;
});
for(i = 0; i < arrayOneCount; i+=1){
alert(arrayTest[0][i]);
}
}
your problem with var arrayOneCount = reportOneArray.length; and you're not changing this value
I'm trying to populate a <span></span> element on the page load with jQuery.
At the moment the value that gets populated into the span is just an integer count.
Here I have named my span userCount:
Users<span id = "userCount"></span>
I am trying to write the value of the span with no success.
$(document).ready(function () {
$.post("Dashboard/UsersGet", {}, function (dataset) {
var obj = jQuery.parseJSON(dataSet);
var table = obj.Table;
var countUsers;
for (var i = 0, len = table.length; i < len; i++) {
var array = table[i];
if (array.Active == 1) {
var name = array.Name;
}
countUsers = i;
}
userCount.innerHTML = countUsers.toString();
});
});
You don't have any usercount variable. Use $(selector) to build a jquery object on which you can call functions like html.
$('#userCount').html(countUsers);
Note also that
you don't need to convert your integer to a string manually.
if you don't break from the loop, countUsers will always be table.length-1.
you have a typo : dataSet instead of dataset. Javascript is case sensitive.
you don't need to parse the result of the request
you don't need to pass empty data : jQuery.post checks the type of the provided parameters
So, this is probably more what you need, supposing you do other things in the loop :
$.post("Dashboard/UsersGet", function (dataset) {
var table = dataset.Table;
var countUsers = table.length; // -1 ?
// for now, the following loop is useless
for (var i=0, i<table.length; i++) { // really no need to optimize away the table.length
var array = table[i];
if (array.Active == 1) { // I hope array isn't an array...
var name = array.Name; // why ? This serves to nothing
}
}
$('#userCount').html(countUsers);
});
Use .html()!
Users<span id = "userCount"></span>
Since you have assigned an id to the span, you can easily populate the span with the help of id and the function .html().
$("#userCount").html(5000);
Or in your case:
$("#userCount").html(countUsers.toString());
Change:
userCount.innerHTML = countUsers.toString();
to:
$("#userCount").html(countUsers.toString());
Instead of:
userCount.innerHTML = countUsers.toString();
use:
$('#userCount').html(countUsers.toString());
You could use
$('#userCount').text(countUsers);
to write data to span
The call back argument should be dataSet rather than dataset?
var AppPatientsList = JSON.parse(JSON RESPONSE);
var AppPatientsListSort = AppPatientsList.sort(function(a,b){
return a.firstName.toLowerCase() <b.firstName.toLowerCase()
? -1
: a.firstName.toLowerCase()>b.firstName.toLowerCase()
? 1 : 0;
});
var DataArray = [];
for (var i = 0; i < AppPatientsListSort.length; ++i) {
if (AppPatientsListSort[i].firstName === search.value) {
var appointment = {};
appointment.PatientID = AppPatientsListSort[i].PatientID;
appointment.ScheduleDate = AppPatientsListSort[i].ScheduleDate;
alert(appointment.ScheduleDate); // Works fine, i get the date...
}
DataArray[i] = appointment;
}
var RowIndex = 0;
var ScheduleDate = "";
for (i = 0, len = DataArray.length; i < len; i++) {
// Throws me error in this place... WHY?
if (ScheduleDate != DataArray[i].ScheduleDate) {
ScheduleDate = DataArray[i].ScheduleDate;
}
}
What's wrong with this code, why i am not able to access the ScheduleDate?
You are only initializing the appointment variable when you are inside the if clause, but you are adding it to the array on every iteration.
If the first element of AppPatientsListSort does not have the value you search for, DataArray[0] will contain undefined.
In the second loop you then try to access DataArray[0].ScheduleDate which will throw an error.
Update:
Even more important, as JavaScript has no block scope, it might be that several entries in DataArray point to the same appointment object.
Depending on what you want to do, everything it takes might be to change
DataArray[i] = appointment;
to
DataArray.push(appointment);
and move this statement inside the if clause so that only appointments are added that match the search criteria.
Further notes: To have a look what your DataArray contains, make a console.dir(DataArray) before the second loop and inspect the content (assuming you are using Chrome or Safari, use Firebug for Firefox).