I created an array of arrays from an api call. The parent array is arrStories. When I display the parent array in console.log, it looks like this:
[]
When I click the little arrow next to [] I get all the child arrays. They each look similar to this:
0: Array(4)
0: "08 Apr 2019"
1: "Avoiding those surprise bills when you stumble out of your insurance network"
2: "https://url"
3: "https://url-of-image"
length: 4
[[Prototype]]: Array(0)
When I try to get the length of the parent array, though:
console.log(arrStories.length); //returns 0
What has happened??
Here is how I filled my arrays:
$.getJSON('my-api', function(data) {
getStories(data); //push stories into an array of arrays
});
orderStories(arrStories); //order by date descending
function getStories(data) {
for (var i = 0; i < data.articles.length; i++) {
var pubDate = data.articles[i].publishedDate;
pubDate = pubDate.slice(5);
pubDate = pubDate.substring(0, pubDate.length - 15);
arrStory.push(pubDate, data.articles[i].title, data.articles[i].link, data.articles[i].images[0].url); //push values into array
arrStories.push(arrStory); //push array into parent array
arrStory = []; //clear original array
}
}
function orderStories(arrStories) {
arrStories.sort(function(a, b) {
var dateA = new Date(a.date),
dateB = new Date(b.date)
return dateA - dateB;
});
}
You do not have an object with .date and you need to process all inside the getJSON function
You likely want this
function getStories(data) {
return data.map(article => {
var pubDate = data.articles[i].publishedDate;
pubDate = pubDate.slice(5);
pubDate = pubDate.substring(0, pubDate.length - 15);
return {
date: pubDate,
title: article.title,
link: article.link,
imageUrl: article.images[0].url
}
})
}
function orderStories(arrStories) {
arrStories.sort(function(a, b) {
var dateA = new Date(a.date),
dateB = new Date(b.date)
return dateA - dateB;
});
}
$.getJSON('my-api', function(data) {
const arrStories = getStories(data)
orderStories(arrStories)
// here you can process arrStories
});
I think it's an issue of your $.getJSON callback happening after you're synchronously calling orderStories on the next line -- I think you want to put orderStories in the $.getJSON callback
I think you're ordering the stories before you've received them
Another approach could look something like this
async function getData () {
return new Promise(resolve => { $.getJSON('my-api', resolve) };
}
getData().then(data => {
const stories = getStories(data);
const orderedStories = getOrderedStories(stories);
});