What is the best way to arrange an array to display country data based on Covid cases in descending order rather than alphabetical order?

This particular code snippet retrieves Covid19 statistics data using an API. Currently, it displays the data for covid cases of all countries in Alphabetical order. However, I am looking to present the data in descending order, meaning that the country with the highest number of cases should appear first in the table.

$.ajax({
  url: "https://api.covid19api.com/summary",
  type: "GET",
  dataType: 'JSON',
  success: function(data) {
    console.log(data);
    console.log(data.Countries);
    var sno = 1;
    $.each(data.Countries, function(key, value) {

      $("#country-wise").append("<tr>" +
        "<td>" + sno + "</td>" +
        "<td>" + value.Country + "</td>" +
        "<td>" + value.NewConfirmed + "</td>" +
        "<td>" + value.NewDeaths + "</td>" +
        "<td>" + value.NewRecovered + "</td>" +
        "<td>" + value.TotalConfirmed + "</td>" +
        "<td>" + value.TotalDeaths + "</td>" +
        "<td>" + value.TotalRecovered + "</td>" +
        "</tr>");
      sno++;
    });
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<table id="country-wise"></table>

Answer №1

Utilize the sort function within the Array object.

$.ajax({
  url: "https://api.covid19api.com/summary",
  type: "GET",
  dataType: 'JSON',
  success: function(data) {
    console.log(data);
    console.log(data.Countries);
    data.Countries.sort((a, b) => b.TotalConfirmed - a.TotalConfirmed);
    var sno = 1;
    $.each(data.Countries, function(key, value) {
      console.log(key + ":" + value);

      $("#country-wise").append("<tr>" +
        "<td>" + sno + "</td>" +
        "<td>" + value.Country + "</td>" +
        "<td>" + value.NewConfirmed + "</td>" +
        "<td>" + value.NewDeaths + "</td>" +
        "<td>" + value.NewRecovered + "</td>" +
        "<td>" + value.TotalConfirmed + "</td>" +
        "<td>" + value.TotalDeaths + "</td>" +
        "<td>" + value.TotalRecovered + "</td>" +
        "</tr>");
      sno++;
    });
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<table id="country-wise"></table>

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

Incorporating a background image into a card component using props

I attempted to add a background image to the card component through props, but the image failed to display on the card. I didn't encounter any errors, and I'm unsure what mistake I might be making. Any suggestions or alternative solutions would b ...

What is the best way to display all checked checkboxes even when the page is reloaded?

I am facing an issue with my website - it is using JavaScript to search for checked checkboxes. $(function () { var $allELements = $('.input-box'); var $selectedElementsListing = $('#selectedElements'); var $selec ...

The automation script for Playwright/Puppeteer is having trouble properly handling `async...await` in a `for..loop` on the `/signup` page

Currently, I am faced with the challenge of automating rate-limit requests using a playwright automation script. The issue arises when the script keeps attempting to sign up with the email <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data ...

Having trouble deserializing a JSON with an extended abstract class in Java using Jackson?

All the classes have been declared as static. The creation of objects occurs within the main() function provided below: import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson ...

Update JSON data in ng-blur event using AngularJS

Could you offer some guidance on how to push the content from a text box into JSON when I click outside of the box? Below is the code for my text box: <input type="text" name="treatmentCost" class="form-control" ng-model="addTemplate" /> And here i ...

My experience with jquery addClass and removeClass functions has not been as smooth as I had hoped

I have a series of tables each separated by div tags. Whenever a user clicks on a letter, I want to display only the relevant div tag contents. This can be achieved using the following jQuery code: $(".expand_button").on("click", function() { $(th ...

Even though I included a key prop for each item, I am still encountering the error message stating that every child in a list should have a distinct "key" prop

I have been trying to retrieve data from a rest API and display it as text on my browser. However, I am encountering the following error: index.js:1 Warning: Each child in a list should have a unique "key" prop. Below is how I have set up the key prop. ...

Looking to update this jQuery pop-up menu script to be compatible with Ajax functionality

I came across this script at The issue arises when the script is called multiple times, resulting in a cascade of pop-outs within pop-outs. I am currently exploring ways to prevent the execution of the script if the pop-out has already been set. Below is ...

Having success loading JSON with AJAX in a local browser, however encountering issues when attempting to do so within the PhoneGap

When I try to load external JSON-data locally in my browser, it displays the data successfully. However, when using a cloud-based build service like PhoneGap for iOS and Android apps, the page loads but without the JSON-data appearing. Can anyone provide a ...

Troubleshooting problem in Java related to encoding with XMLHttpRequest

Currently, I am utilizing XMLHttpRequest for an ajax call to my server. Let's consider the call: http = new XMLHTTPRequest(); var url = "http://app:8080/search.action?value=ñ" http.open("GET",url,true); http.setRequestHeader("Content-type", "applica ...

The Correct Way to Implement Google ReCaptcha

I've developed a PHP contact form that performs validation using AJAX/JSON on the server side. The errors are then passed to Javascript for display and adjustments to the HTML/CSS. My challenge now is to integrate Google ReCaptcha with AJAX validatio ...

Encountering a problem in Django when attempting to serialize decimal points, error message reads: 'ValuesListQuerySet' does not contain the attribute '_meta'

I'm trying to serialize a FloatField model instance in django, specifically within a management command. Here's the code I have: def chart_data(request): i = 1 chart = open_flash_chart() chart.title = t for manager in FusionMa ...

What is the reason for needing a page reload in Javascript or JQuery?

I'm curious why Javascript or jQuery require a page reload before applying certain effects. CSS updates in real-time, as demonstrated by the following example: This changes dynamically without needing to refresh the page @media all and (max-width:7 ...

Convert a number to binary in JavaScript, but display the result as infinity

data = parseInt(num); bin =0; pow=1; var rem=0 ; while(data != 0){ rem = data % 2; data = data / 2; bin = rem * pow + bin; pow = pow *10; } document.write(bin); I encountered an issue with my JavaScript code. Even though the example should output 11011 ...

ESLint detecting error with returning values in async arrow functions

Currently facing a minor inconvenience instead of a major problem. Here is the code snippet causing the issue: export const getLoginSession = async (req: NextApiRequest): Promise<undefined | User> => { const token = getTokenCookie(req) if (!t ...

The task of mapping an array of objects with nested values using JavaScript is proving to

Attempting to convert an array of objects with nested values in child objects like: const objs = [{ "B": { "value": 1, }, "D": { "value": "45" }, "E": { "value": "234" }, ...

Performance issues with Datatables server side processing

Utilizing Datatables server-side processing with PHP, JQuery, Ajax, and SQL Server database, I encountered slow performance in features such as pagination and search. Despite working with moderate data, there is a delay of over 40 seconds when using the se ...

java.lang.IllegalArgumentException: The provided string is either empty or null

I have recently started working with Firebase and encountered an issue while trying to implement a login functionality. Whenever I attempt to click the button without filling in the fields, the application crashes even though I have written code to handle ...

Displaying multi-dimensional arrays through the console in JavaScript and showcasing their elements

My array is supposed to have 140 indexes in a single format like this: array:[0-140] //however, it currently appears as: array: [ 0: [0-99], 1: [100-140] ] I've confirmed multiple times that it is just one array of objects. Why is it s ...

Extracting multiline value from a textarea using JavaScript

I'm trying to extract a multiline value from a textarea using JavaScript or jQuery and store it in a cookie. Below is the code snippet I am using: HTML: <textarea id="cont" cols="72" rows="15"> JavaScript: var txt = $('#cont').val( ...