I am trying to push elements onto an array.
EDIT
task.prototype.goTest=function(){
for(a = 0; a < test.length; a++) {
if(this.testnumber != test[a].number) {
//it will only loop 8 times under conditional statement
group = {
title: test[a].Title,
ID: test[a].ID,
contents: []
};
this.company.push(group);
this.testnumber = test.number[a];
}
//outside of if conditional statement.. it will loop 15 times
//i want every test[a].conetents get pushed to group.contents array.
//this.company is the final variable I need for this function...
group.contents.push(test[a].contents);
}
console.log(this.company);
}
However, when I do
console.log(this.company);
I see 8 elmements with only 1 element in each group.contents array. The ideal situation is to have 8 elements with 2 to 3 elements in the group.contents array.
this refers to the object in the function.
Any idea how to solve my issue?
You are making a new group object each loop, so the reference to group.contents is only the current one, it does not reference the previously created group objects.
So, each time you call group.contents.push, you are only pushing onto the object created in that loop iteration.
Related
I am using jQuery and got an response from API by using $.ajax. I want to grab the Arrays length from inside each object and display that in the html page. This is what I have done so far.
Here is the API response, i did breakdown of the last object, which contains an array and player names:
{_type: "InjuredPlayers", flaggedTokens: Array(1)} //1 injured player name
{_type: "InjuredPlayers", flaggedTokens: Array(3)} //3 injured players names
{_type: "InjuredPlayers", flaggedTokens: Array(5)} //5 injured players names
{_type: "InjuredPlayers", flaggedTokens: Array(2)} //2 injured players names
>flaggedTokens:Array(2)
>0:{offset: 0, token: "John", type:"UnknownToken"}
>1:{offset: 1, token: "Adam", type:"UnknownToken"}
length: 2
>_proto_:Array(0)
_type: "InjuredPlayers"
>_proto_: Object
In order to grab the length of the Array I can do any of these 2 methods according to this Get length of array inside object
console.log(response.flaggedTokens.length)
1
3
5
2
OR
console.log(response["flaggedTokens"].length)
1
3
5
2
My Failed Attempts: I assigned this output to a variable and tried to loop through and output by doing this:
$.ajax(gameResponse).done(function(response) {
let injuredPlayers = response.flaggedTokens.length;
let injuredPlayersArray = [];
for (let i = 0; i < injuredPlayers.length; i++) {
injuredPlayersArray.push(injuredPlayers[i])
}
$('.injured_players').html(injuredPlayersArray[i])
})
<div class="container">
Team One Total number: <span class="injured_players"></span> //should be 1
Team Two Total number: <span class="injured_players"></span> //should be 3
Team Three Total number:<span class="injured_players"></span> //should be 5
Team Four Toal number: <span class="injured_players"></span> //should be 2
</div>
Clearly I made some mistake which I can't seem to figure this out by myself. I was hoping if someone can guide me through the right direction.
To start with, in your for loop, you are returning the push action, but that's unnecessary and it kills the loop on the first iteration. Also, you have already set the length of the array to a new variable, but then in your for loop, you try to get the length of the new variable. Lastly, you declare injuredPlayersArray in your ajax statement, but based on your post, you recieved 4 separate api responses, so it should be declared outside of your ajax call so that the array doesn't get overwritten with every new call. And you don't need a for loop as you're only working with one array. Here is what it should look like.
let injuredPlayersArray = [];
$.ajax(gameResponse).done(function(response) {
let injuredPlayers = response.flaggedTokens.length;
injuredPlayersArray.push(injuredPlayers)
})
Your other mistake is that you are trying to dynamically display the value in the proper html tag, but you're setting the value for every span tag at the same time. So after your loop is finished, they would all say 2.
To fix that you can add a for loop after all of your api calls are completed (aka NOT inside a $.ajax().done()):
for (let i = 0; i < injuredPlayersArray.length; i++) {
$('.injured_players').eq(i).html(injuredPlayersArray[i])
}
Note: .eq() returns a set of DOM elements that match the selector it is called upon. So $('.injured_players') matches 4 elements on your page and in your for loop, it finds the i-th element in that set (so index 0 is equal to the first span tag) and sets the html for that element.
Note 2: There is an assumption I had to make with your api calls. From the way your api call is storing the length of the flaggedToken array in your response, it seems each ajax response returns a single object with the array of injured players and that you will have 4 separate api calls. However, if that's not the case and the response returns a array of objects, you will need to iterate over the array and get the length for every array in every object one at a time. You can also then ignore my suggestion to move the declaration of injuredPlayersArray to outside the api call. And the second for loop i wrote would go inside the api call.
so I have a node js / websocket server going, where I want to store multiple instances of setInterval timers...
I have them stored in an array of [timer, client] objects that I want to step through when a client disconnects, then step through the array and turn off all the timers that are paired with the disconnecting client before removing them from the array.
Removing the objects connected with the clients is working, however, the timers are not stopping...
I am declaring the timers like this -
clientSchedulePairs.push([setInterval(makeVisibleHandler, master_period, item, name), client]);
then trying to turn the schedule off like this when a client disconnects-
clearInterval(clientSchedulePairs[i][0]);
in my research i found this question -
clearInterval() is not stopping setInterval() - Firefox Extension Development
which says that I need to make a timer a global variable? but that isnt helping because if I have multiple timers for multiple clients how can i make them global variables?
I am storing them in a global const array that is declared globally such as-
const clientSchedulePairs = [];
however it is not working...
any idea on if the reason its not working is because its not declared as a global variable? or how I can get around this and get it to work? (i already tried declaring the schedule as a variable in my method before adding it to the array)
thanks.
UPDATED---
i got it working turning off the timers --- not sure if it had something to do with the way the client was disconnecting, after I removed my for loop into an external method that took in the client socket as a variable, then looped through my array of client / timer pairs and checked for the clients and removed them it started working. However, I am running into a kind of strange issue now...
as i said, i am looping through a clientTimerPairs array and checking if the client paired to that timer is === to the client_socket that was passed in from when the method was called when a client disconnects, in this loop, calls this--
clearInterval(clientTimerPairs[i].interval);
and the timers turn off, however I had a problem removing the client - timer tuples from the clientTimerPairs array now
i couldnt get them to remove from the array, so i changed it to work like this-
var indexToRemove = [];
for (var i = 0; i < clientTimerPairs.length; i++) {
if (clientTimerPairs[i].pairedClient === client_socket) {
clearInterval(clientTimerPairs[i].interval);
indexToRemove.push(i);
}
}
for (var i = 0; i < indexToRemove.length; i++) {
console.log('removing index ' + indexToRemove[i] + '...');
clientSchedulePairs.splice(indexToRemove[i], 1);
}
however, even if i console print indexToRemove, and it has all index 0 - 6 in it, (because during testing i only connected 1 client with 6 timers), it should be stepping through clientTimerPairs and removing every single index so clientTimerPairs is empty, however, for some strange reason instead of going from 6 to 0 size, the array always ends up at 3 size!
even though it prints the removing index line 6 times and says it is removing index 0 - 5, 3 items are always left over in the clientTimerPairs array!
any idea why this might happen?
That push statement does not provide a proper key-value pair. How about using es6 Map to secure actual pairs?
However, it should work as intended.
const timers = [];
for (let i = 0; i < 5; i++) {
timers.push([setInterval(runTimer.bind({ id: i}), 100), i]);
}
function runTimer() {
console.log(`running for id ${this.id}`);
}
setTimeout(() => {
console.log('clearing timers')
for (let i = 0; i < timers.length; i++) {
clearInterval(timers[i][0]);
}
}, 2000);
Edit regarding the addition to your post
The splicing does exactly as it is intended to do. Say you have an array of 6 elements. You are clearing elements from the array using an array of indices and remove the first element. That array length becomes 5. The second index points to the 6th element. When you try to splice the 6th element by its index, nothing happends. This is because you removed one element from the array, which made the 6th element shift to the 5th position.
A simple solution could be using es6 filter:
let items = ['one', 'two', 'three', 'four'];
let indices = [1, 3];
items = items.filter((item, index) => indices.indexOf(index) === -1);
This returns an array with the first and third elements.
I used nodeJs to do some simple data processing. Links are array with objects with a source and a target.
For example:
Links=[{source: 'a', target: 'b'},{source: 'b', target: 'c'}]
Now i want to add 4 link to links but it did not work
for(var i=0;i<Links.length;i++){
for(var j=0;j<2;j++){
Links.push({
source: 'yo',
target: 'yo'
});
}
}
The entire program stuck here (goes for infinite loop).
Very simply you are adding items to the list you are pushing to so you can never reach the end. The simplest way around would be to save the length of the array to a variable and use that rather than calculating Links.length with every iteration.
Using the length property of an array will cause an infinite loop if you add items to the array in the loop. You should store the length in a variable instead of using the length in the condition.
Using nested loops in this situation might cause issues if there are more than two elements in the array. At the moment, you add two element for each element already in the array. It means it will add 6 links it there were 3 links in the array at the start of the loop, 8 if there were 4, and so on.
You could do some like this to strickly append 4 links to your array no matter how many link there were at the start.
startLength = Link.length;
do {
Link.push({
source:'yo',
target:'yo'
});
} while (Link.length < startLength + 4);
This question already has answers here:
Loop through an array in JavaScript
(46 answers)
Closed 8 years ago.
trying to create Create an array containing the names of at least three (3) fast food items and then, using a ‘for’ loop, display the array name, index number, and food item as shown below.
Fast Foods
fastFoods[0] is pizza
fastFoods[1] is burgers
fastFoods[2] is french fries
I can get the array but not the for to display like this.
Iterate over an array with for :
each array has a length property.Array indexing starts from 0 but length property starts count from 1.So in your for loop you have to set a condition which will iterate until the end of array is reached.for loop to iterate over an array has the following structure
for(i=0;i<array.length;i++){ // in your case it will be fastfood.length
//access elements here
}
++ is an increment operator.It will increase the value of i by one after each iteration.It is equivalent to i=i+1;
and inside for loop you can access the elements using the following structure
arrayName[index];
here arrayName is your array name( in this case fastfood) and index is the current i value;
so for your case it will be
fastfood[i]
To create an array with for :
first create a new array called fastfood
var fastfood=new Array() //or
var fastfood=[] // [] is a valid array notation
if you are goning to create an array using for loop you have to set a condition about how many elements you want to set in your array.For this case the structure will be
for(i=0;i<n;i++){} // here n is your desired number;
inside the for loop you can have a prompt method .It will allow you to enter a food element after each iteration.Prompt is not a good idea,but i assumed you are new to JS.Here is the structure:
fastfood[i]=prompt('enter food name');
var fastFood = ['pizza', 'burgers', 'french fries'];
for (var i = 0; i < fastFood.length; i++) {
console.log('fastFood[' + i + '] is ' + fastFood[i]);
}
I am looking to create a set of dynamically created arrays stored inside an object. the outcome would be something similar to this...
object.array0.length = 5, object.array1.length = 4, etc
the name of the array would be generated from within a for loop based on a numerical value declared elsewhere in the application.
Here is the code that I have...
var obj = {};
var weekNum = 4;
for(i=0; i < weekNum.length;i++) {
obj['week'+i] = [];
obj['week'+i].push(day);
console.log('days stored in week0: '+obj.week0.length);
}
What seems to be happening is that obj['week'+i] doesn't realize that it is an array, and the push command doesn't seem to be enough to make it think so. So as a resulting value of obj.week0.length is always 1 with the actual value just being replaced each time as opposed to the array being incremented.
Also fyi,
The parameter day in the above code would be passed in from another function representing any chosen day (Mon, Tues, etc)... However, the sequence and the amount of days passed in could differ but will never exceed 5 (m-f).
Looks like a logic problem to me. You're always only inserting 1 day into the array unless day represents something else altogether.
var obj = {};
var weekNum = 4;
// var was missing :)
for(var i = 0; i < weekNum.length; i++) {
// check if entry exists before creating new.
obj['week'+i] = obj['week'+i] || [];
// you're always only inserting 1 value inside the week array
// don't you want to loop through the number of days
// and insert a day entry for *this* week for each day. like this?
// days is another array of, hmm.. days
for(var j = 0; j <days.length; j++) {
obj['week'+i].push(days[j]);
}
console.log('days stored in week0: '+obj.week0.length);
}
It is not changing, because each time through the loop you reset the value to [], then push onto it. Try moving the obj['week'+i] = [] to outside the loop.