I'm new to using JSON and Javascript, but I am trying to sort various values of the JSON file provided by Reddit. In the console, I do see the array and the JSON values from the console.log(posts) print. However, the console.log(posts.length) statement returns 0 and nothing is displayed to the screen, which I suspect is due to how I am storing and/or retrieving the JSON values in the array.
var minVotes = 5;
var subreddit = "askreddit";
var posts = [];
//Retrieve JSON from Reddit using JQuery
$.getJSON("https://www.reddit.com/r/" + subreddit + "/rising.json?limit=50", function foo(result) {
$.each(result.data.children.slice(0, 50), function(i, post) {
if (post.data.ups > minVotes) {
//Push JSON data to array to be sorted later
posts.push(post.data);
}
})
})
//Sort the array
posts.sort(function(a, b) {
return parseInt(a.data.ups - a.data.num_comments) - parseInt(b.data.ups - b.data.num_comments);
});
console.log(posts);
console.log(posts.length); //returns 0 ???
//Display the content, which doesn't work
for (var i = 0; i < posts.length; i++) {
$("#reddit-content").append('<br>' + "Title: " + posts[i].title);
$("#reddit-content").append('<br>' + "Url: " + posts[i].url);
$("#reddit-content").append('<br>' + "Upvotes: " + posts[i].ups);
$("#reddit-content").append('<br>' + "Comments: " + posts[i].num_comments);
$("#reddit-content").append('<hr>');
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="reddit-content"></div>