Appending an array with a for loop - javascript

I'm trying to write a function to append an array with a for loop. The data I'm trying to append is in a JSON repsonse. However, I keep getting x10 Array[] in the web console instead of one array with all the data. When I run console.log(dates[0]) I get returned in the web console "undefined". This tells me the data isn't even making it into the array. When I run console.log(time) I return x10 peices of data from the JSON I want but of course its not in the array. Any ideas? Thanks.
function mostRecent(time) {
var dates=[];
for (var i = 0; i < time.length; i++) {
dates.push(dates[i]);
}
return console.log(dates);
}

You are pushing dates[i] with every loop cycle. And since dates array keeps being empty, you are actually pushing undefined.
Just replace dates.push(dates[i]) with dates.push(time[i]).
Note: You should return dates instead of console.log.

Related

Can not loop JSON object in Javascript

I apologize there is going to be a lot of attachments to explain this.
I am pulling a JSON object, storing it in SQLite, then later retrieve it and trying to compare it with a newer pull to check for updates. This works perfectly in simple, one level JSON. The trouble is with nested JSON.
I console.log the datasets before comparison (the first array(4) is the new set, the second array(4) you see in this picture is the old set, previously retrieved from the Same API, stored in SQLite and then retrieved on future loading
datasets
they look identical and both are valid JSON objects according to jsonlint.com,
I was able to loop through the new JSON and "collapse" it to a single level array so I can use it later to compare. With this code I can see that the "links" array is correct
new links array
newData.forEach(m=>{
console.log('new data loop 1');
Object.entries(m as Record<string, string[]>).forEach(([key, value]) => {
console.log('new data loop 2');
if (key == 'links'){
console.log('new value');
console.log(value);
for (let i=0; i< value.length; i++){
newData2.push(value[i]);
}
// newData2.push(value);
}
})
})
However, when I tried to do the same loop for the old JSON object (stored in SQLite then retrieved), Chrome debugger thinks the "links" array has a length of zero, which from my research it could just mean it is recongzied as an object and therefore no length, never mind it worked fine for the new JSON object.
old links array
The issue:
4. I have no way to loop the old JSON object, here are three different ways to try to loop it and none of them makes into the loop.
oldData.forEach(m2=>{
console.log('old data loop 1');
Object.entries(m2 as Record<string, string[]>).forEach(([key2, value2]) => {
console.log('old data loop 2');
if (key2 == 'links'){
console.log('value');
console.log(value2);
for (var ii=0; ii< value2.length; ii++){
console.log('old data loop 2.1');
}
console.log('old data loop 2.5');
value2.forEach(m3=>{
console.log('old data loop 3');
Object.entries(m3).forEach(([key3, value3]) => {
console.log('old data loop 4');
console.log(key3 + '...' + value3);
});
})
for (var key in value2) {
console.log('old data loop 4');
if (value2.hasOwnProperty(key) ){
console.log( "key:"+key+", val:"+value2[key] );
}
}
}
})
})
The result looks something like this, so you can tell none of the attempts to loop the old "links" object works.
no loop happening
5. so there is obviously something about the old nested JSON object that is causing problems with the looping. I really appreciate any help as I have worked on this off and on for days and can't figure this out. The ultimate goal is to compare the two nested JSON objects so if there are other ways I am open to that too.
I solved this. The problem had nothing to do with how JSON objects is looped. It was an async problem. I did something after I load the array and I forgot to put that in a Promise so that even though Chrome debugger shows me the array had content, in real time it was empty!
Thanks #Serge, I did take your advice and just use string.search function now instead of trying to flatten the arrays manually then compare.

Array not being written to - Async NodeJS

var songs = [];
request.get(getSongs, function(error, response, body){
append(songs,body);
});
function append(arr, data){
for (let j = 0; j < data.items.length; j++) {
console.log(data.items[j].track.name);
arr.push(songs,data.items[j].track.name);
}
}
console.log(songs); //outputs '[]'
I've google a lot and I'm not sure what I'm doing wrong.
For some context, request.get() returns between 1 and 20 objects, and I'd like to add an attribute (or more) of all of them to the array 'songs'. They console.log() correctly and their positions are correct, but when I log the array, it appears to be empty.
What am I doing wrong? Thanks for the help.
The issue you have here is that you're logging the array synchronously. Currently, your program currently runs as follows:
Defines an empty array
Kicks off a request to get songs
Defines your append function
logs the empty array
Gets back the songs
Populates the array with the songs.
If you console.log after your append call you'll see you have all the songs in your array.

How do I assign my get response data to an array in the order I sent the request

I have a rest.get request inside a for loop, that is sending around 20 queries (based on data from a previous request that changes the query each time). My problem is that it seems to be running the for loop completely through and then the queries run asynchronously and are responding with the data that returns the quickest instead of consecutively. If I console.log the index of the forloop inside the .end function, it is undefined until the forloop is finished and then it is the final number (even though it is all inside the for loop). I am trying to save (push to an array) the data in the same order I am sending the request, so I can match the data with the previous get response list that I’m printing out. Is there a way to assign my response data to an array in the order that I am sending the request instead of first come first serve?
// this function is being called inside the previous query
function carData(req, res) {
var carNameJson = [];
var resultToJson = [];
//singleCars.length is defined in a previous query and is an array of car IDs
for (var index = 0; index < singleCars.length; ++index) {
//Grab each individual car ID and concatinate it into a Query
var carNames = singleCars[index];
var carQuery = "https://queryinfo";
var finalSingleQuery = "carQuery + carNames";
// puts the data into an array of JSON objects
carNameJson = {
carID: carNames
};
// result is a global variable assigned as an empty array
// it list all the car IDs in a JSON format
result.push(carNameJson);
rest
.get(finalSingleQuery)
.proxy("http://proxyinfo")
.end(function(resp) {
resultToJson = {
carInfo: resp.body
};
// resultInfo is a global variable assigned as an empty array
resultInfo.push(resultToJson);
return resultToJson;
});
}
}
This code all works, but it gives me the data out of order, so I can't match the car information to the list of car IDs. I am new to node, so I may be doing this all wrong. Any help would be appreciated!
You could use the index variable to target where to store the response. For that you must make sure the index variable is local to the for body, which you can achieve with let (instead of var):
for (let index = 0; index < singleCars.length; ++index) {
// ...
// store directly at the correct index:
resultInfo[index] = resultToJson;
You might also be interested to know when you have all results. This you can do with this condition, just after the assignment to resultInfo[index]:
if (resultInfo.filter(Object).length === singleCars.length) {
// maybe call a callback here.
}
You're performing restful response inside of a for loop. Instead, consider building a complete JSON object filled with all the data the client will need (in other words, send it all as 1 big response, instead of lots of little responses).
Use the for loop to build the JSON, then outside of the loop, perform your 1-time restful response.
That way you don't have to worry about the data coming through out of order, and the response is complete and not missing important information like index.

Angular Js stuck in inserting the array values after sorting

Hello guys i am stuck in angular js.
What i have to do is to show the steps of selectionSort and the code i made is
var myApp = angular.module('myApp',[]);
var arraymain = [];
myApp.controller('myController',function($scope) {
$scope.array2 = [];
$scope.selectionSort = function(list) {
n=list.length;
temp2 = list;
for(i=0; i<n-1; i++) { //need to do n-2 passes
i_min=i;
//finding mining index
for(j=i+1;j<n;j++){//ith position: elements from i till n-1 candidates
if(temp2[j]<temp2[i_min])
i_min=j; //update the index of minimim element
}
temp=temp2[i];
temp2[i]=temp2[i_min];
temp2[i_min]=temp;
alert(temp); //It shows as needed
$scope.array2.push(temp2); //Here i am having problem it saves the sorted final array i.e the last every time of loop but i want to save current array on every outer loop execution
}
return list;
$scope.selectionSort([3,2,3,4,5,1,2]);
console.log($scope.array2[0]);
console.log($scope.array2[1]);
console.log($scope.array2[2]);
});
Sorry for my bad English.
It's not clear what you need to do. I'm pretty sure you've got a real mess on your hands beyond your main problem, and using Angular is only making it worse.
If your goal is to console.log the state of the array at each step of the selectionSort outer loop, then you need to run console.log at the bottom of each loop.
The first thing that looks fishy suspicious is:
$scope.array2.push(temp2);
If you run console.log(array2) at each step of the loop as I suggested, you need this line to be instead:
$scope.array2 = temp2;
That way, you overwrite array2, which holds the state of the array at each iteration of the for loop. Then you log it. Appending each state to a larger array, and then running console.log on each item in that array is not the best way to do this.
But, I'm not sure that's what your problem is.

Javascript resetting an array

I'm having with some very strange behaviour when I try to reset an array; eg:
data.length=0;
where data is an array. I'll try and include only the relevant code here but basically what I;m doing is on each iteration of my program I'm populating the array with updated values and the array then is used in another function. But when I reset the array the function appears to get the values on the first iteration but none afterwards.
However when I don't reset the array then the function gets the values, but also the older values. I don't want this, as I only want the new updated values only. This is a code snippet:
var buffer = [['1',[0]],['2',[0]],['3',[0]],['4',[0]]];
var dataset = [];
ws.onmessage = function(evt){
dataset.length=0;
var distances = JSON.parse(evt.data);
console.log(distances);
for(var i=0; i<buffer.length; i++) {
if(buffer[i][0] == distances.miles) {
buffer[i][1][0]++;
}
//console.log(buffer);
dataset.push(buffer[i][1][0]);
draw();
//console.log(dataset);
}
}
The function uses the dataset array to redraw a chart.
I've tried to keep it simple here, but the full function is here.
I really don't know what's causing this unexpected behaviour.
EDIT:
console.log(dataset) shows the new updated values, but somehow dataset.length=0; is preventing the updated array to be used by the draw() function. As without the resetting of the array the array can be used by the draw() function.
EDIT:
I've tried to not reset the array but instead get the last 4 elements and put them in a new array and then send them to the draw(), but still the same odd behaviour:
x = dataset.slice(-4);
console.log(x);
draw();
But if I don't do that or don't clear the array, then draw() render a 'wrong' chart. I can't see what is wrong.
THE problem somehow seems to reside with the resetting of the array and that because of this it means the draw() function appears to be called only once at the first iteration.
Please, Please help
You don't need to set length at all. To clear a list of all value, just set it to an empty list:
dataset = [];
Looking at your code, I'm not sure, but why do you even have dataset? You don't ever read anything out of it, and you say you want to clear it every time thru the array.
Do you mean do to something like:
for(var i=0; i<buffer.length; i++) {
if(buffer[i][0] == distances.miles) {
buffer[i][1][0]++;
}
dataset.push(buffer[i][1][0]);
}
draw(dataset); // draw outside the loop, using dataset.

Categories