Selecting the most popular post from a Facebook group

Here is the JSON file that I am currently using JSON.parse(); in Google Apps Script. Currently, I have found a temporary solution with this code by selecting posts that have more than 15 likes. However, my goal is to be able to select the post with the most likes regardless of whether it has more than 15 likes or not.

function repost() {
var UsrAccess_token = "xxxxxxxxx"
var graph = "https://graph.facebook.com/xxxxxx/feed/?access_token="+UsrAccess_token+"";
var jsondata = UrlFetchApp.fetch(graph,{method:"get"}).getContentText();
var object = JSON.parse(jsondata);
var item = object.data;
var currentTime = new Date();
var year = currentTime.getUTCFullYear();
var month = (currentTime.getUTCMonth()) + 1;
var day = (currentTime.getUTCDate()) - 1;
if (day <= 9) {var day = "0"+day+"";}
if (month <= 9) {var month = "0"+month+"";}
var utime = ""+year+"-"+month+"-"+day+"T";
try {
var i = null;
for (i = 0; item.length > i; i += 1) {
var pubDate = item[i].created_time;
if (pubDate.match(utime)) { var likesdata = item[i].likes.data; var len = likesdata.length;
                           if (len > 15) {var popular = item[i].link;}}


}} catch(err) {
   var err = "ERROR";
}
}

Answer №1

To set a default value for a variable, you can use something like var maxLikes = 0; and compare it with the len variable.

An example of the code would look like this:

function repost() {
var UsrAccess_token = "xxxxxxxxx"
var graph = "https://graph.facebook.com/xxxxxx/feed/?access_token="+UsrAccess_token+"";
var jsondata = UrlFetchApp.fetch(graph,{method:"get"}).getContentText();
var object = JSON.parse(jsondata);
var item = object.data;
var currentTime = new Date();
var year = currentTime.getUTCFullYear();
var month = (currentTime.getUTCMonth()) + 1;
var day = (currentTime.getUTCDate()) - 1;
if (day <= 9) {var day = "0"+day+"";}
if (month <= 9) {var month = "0"+month+"";}
var utime = ""+year+"-"+month+"-"+day+"T";
try {
  var i = null;
  var maxLikes = 0; 
  for (i = 0; item.length > i; i += 1) {
    var pubDate = item[i].created_time;
    if (pubDate.match(utime)) { 
      var likesdata = item[i].likes.data;
      var len = likesdata.length;
      if (len > maxLikes) {
        maxLikes = len;
        var popular = item[i].link;
      }
    }
  }
} catch(err) {
   var err = "ERROR";
}

}

I hope this explanation is helpful!

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Check if the data-indices of several div elements are in sequential order using a jQuery function

Is there a way to implement a function in jQuery-ui that checks the order of div elements with data-index when a submit button is pressed? I have set up a sortable feature using jQuery-ui, allowing users to rearrange the order of the divs. Here is an exam ...

Invoke Office script from beyond MS Excel WebApp

Within the Excel WebApp on Office 365, users have the ability to incorporate Office Scripts through the "Automate" tab. These scripts utilize JavaScript syntax and can automate Excel functions similar to a VBA macro, specifically designed for the Excel Web ...

Querying a MongoDB collection for a specific entry based on its ID

Is it possible to update a user story in a project using MongoDB? I am looking to update the fields of a specific user story within a project by selecting the project based on its id and then selecting the user story within that project based on its id. ...

Is bower install failing to detect a local npm package?

After running bower install, I encountered the following error message: $ bower install module.js:340 throw err; ^ Error: Cannot find module 'minimist' at Function.Module._resolveFilename (module.js:338:15) at Function.Module._l ...

Exploring the intricacies of React's useEffect: Solving the challenge of updating data when two separate dependency arrays are

I am facing an issue with two different useEffect hooks where the dependency arrays are different. const [dateFilterSort, setDateFilterSort] = useState({ queryText: initialQueryText(params.sortName), cardText: initialCardText(params.sortName), ...

The Typescript compiler is throwing an error in a JavaScript file, stating that "type aliases can only be used in a .ts file."

After transitioning a react js project to react js with typescript, I made sure to move all the code to the typescript react app and added types for every necessary library. In this process, I encountered an issue with a file called HeatLayer.js, which is ...

Showing data retrieved from a JSON file on an Android device

Within my project, I have a json file stored in the raw folder that contains the following code (among other things): { "Monday": [ { "time": "09:15", "class": "Nature", "room": "AL32" }, { "time": "10:15", ...

Converting a lengthy string of coordinates into latitude and longitude in Flutter

From a Json API call, I am receiving a group of latitude and longitude coordinates formatted as a long string in the "lineStrings" block. Typically, I would expect individual latitudes and longitudes that I could iterate through, but instead, I have this ...

Struggling to make jQuery code function properly in Wordpress, despite attempting to use noConflict

I have created a custom image grid gallery in WordPress using HTML and CSS, complete with popups and sliders. I had to code it myself because I couldn't find a suitable plugin that matched my design preferences. I have tested the functionality on my ...

Unraveling a date field from JSON with AngularJS filtering

Extracting data from JSON file shows /Date(1435837792000+0000)/ How can I format the date to appear as Oct 29, 2010 9:10:23 AM? ...

Encountering the error message "require is not defined" in the browser while utilizing gulp-browserify for my React.js modules

I am currently working on using gulp-browserify for creating a bundle.js file that will be utilized in the client's browser to initiate rendering of React components. Below is my App.js file: /** @jsx React.DOM */ var React = require('react&apo ...

JavaScript will not prevent PHP form submissions from executing

I am currently facing an issue with JavaScript where it displays an error window, but surprisingly does not prevent the form submission. I have been trying to figure out what exactly is causing this problem without much success. Below is the code I am work ...

AngularJS is encountering an issue with the callback function, resulting in an error

Currently, I am utilizing the $timeout service in Angular to decrease a variable from 100 to 1 in increments of 1/10 seconds. Although I understand that using the $interval service would be a simpler solution, for this particular scenario, I am focused on ...

What is the reason behind React deciding to skip the final question, even though it has been accurately saved to the

A simple web application was developed to calculate risk scores by asking five questions, with additional points awarded if a checkbox is checked. Despite extensive hours spent debugging, a persistent bug remains: the final question does not appear on the ...

Getting a JSON response from an ASP.NET webpage

I'm currently faced with a problem and have multiple solutions at hand. I am seeking input on the feasibility of these options. One approach involves returning a JSON object from my server side code, but I lack the knowledge on how to execute this eff ...

What is causing the question mark symbol to appear at the beginning of my ajax response?

Below is my JavaScript code: $('#tags').select2({ tags: true, tokenSeparators: [','], createSearchChoice: function (term) { return { id: $.trim(term), text: $.trim(term) + ' (new tag)&ap ...

Issue with ng-disabled not functioning properly for href tag within list item

Is there a way to prevent clicking on the <a> tag within a list item in a UI list so that the associated <div> is not displayed when clicked (excluding the last list item)? I have attempted using ng-disabled directly on the list item attribute ...

Combining React state value with an HTML tag would be a great way

I am facing an issue while trying to concatenate the previous value with new data fetched from an API using a loop. Instead of getting the desired output, I see something like this: [object Object][object Object],[object Object][object Object] Here is ...

Unable to transform Symbol data into a string - Error when making a React AJAX delete call

I'm encountering an issue where I am getting a Cannot convert a Symbol value to a string error in the console. My tech stack includes React v15 and jQuery v3. https://i.stack.imgur.com/qMOQ8.png This is my React code snippet: var CommentList = Reac ...

I'm curious if there is a method to extract and retrieve color text information from JSON using Kotlin

I'm currently working on parsing and extracting data from JSON. However, I would like the respective color to be displayed instead of just the color name. For example: { "id": 1, "name": rose, "color ...