Ordering AJAX response outcome in an ascending manner

Every time the page is refreshed, there seems to be a problem with how the fund names are arranged. They should always be displayed in the order fundI, fundII, fundIII, and so on no matter how many times the page is reloaded.

I've experimented with different styles but have not been able to find a solution. Everything looks good except for the issue of the arrangement mismatch.

Below is my code snippet:

  
$(document).ready(function () {
    $.ajax({  
        type: 'GET',
        url: 'http://datarecapture.premiumpension.com:8089/api/Prices/GetAllFundNames',
        contentType: "application/json"
    }).done(function(data) {
        $.each(data.result, function(i, ele) {
            var detail = {};
            detail.id = ele.FUND_ID;
            detail.name = ele.FUND_NAME;

            $.ajax({
                type: 'GET',
                url: 'http://datarecapture.premiumpension.com:8089/api/Prices/GetCurrentFundPrice?fundId=' + ele.FUND_ID
            }).done(function(data) {
                console.log(data.result);
                var sortedData = data.result;
                sortedData.sort(function(a, b){return a-b});
                
                var id = data.result.FundID;
                detail.price = data.result.UnitPrice;

                var tile = buildTile(detail);
                $('#tile-holder').append(tile);
            })
        })
    });

    function buildTile(detail) {
        detail.sort
        return '<ul style="list-style: none;">'
        + '<li>' + detail.name + '</li>'
        + '<li>' + detail.price + '</li>'
        + '<li><a href="#">View History</a></li>'
        + '</ul><hr>';
    }
});

Answer №1

As mentioned by @Pointy, it is recommended to utilize localeCompare for string ordering.

...done(function(data) {
  var sortedData = [];
  for (var i in data.result) sortedData.push(data.result[i]);
  sortedData.sort(function(a, b) {
    return a.name.localeCompare(b.name)
  });
  ...

Additionally, there appears to be an error in this particular function:

        function buildTile(detail) {
            detail.sort
            return ...

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

Show the contents of an array by utilizing the getJSON method

Currently, I have a function within my code that I am calling using jQuery's getJSON method. Below is the function: public JsonResult GetItems() { var items = (from x in GetAllItems() select new { x.ItemID, x.ItemType.Name, x.Des ...

encountering difficulties with installing dependencies using yarn or npm

After cloning a repository, I attempted to install the dependencies using npm install or yarn but encountered the following errors: For Yarn: https://gyazo.com/2fdf52c4956df2e565cc0b1cedf24628 For npm install: https://gyazo.com/a1d197e9ead89dbe4a7d3c5b8f ...

Is it possible to implement a while loop in React?

Issue: I am facing a challenge while attempting to generate an array of 4 elements from a list using a while loop, but it seems to result in an infinite loop. const [options, setOptions] = useState([]); const fetchElements = () => { while(options. ...

Using jq and node.js to translate AWS EC2 tags

Seeking assistance with transforming this array of EC2 tags using jq and node.js: [ { Key: 'Name', Value: 'xxx' }, { Key: 'role', Value: 'yyy' } ] I want to transform it to: { name : 'xxx', ro ...

Vue.JS encounter a hiccup while attempting to store data in the local storage

My application is set up to fetch data from a rest api, and it consists of two key components: 1 - (main) Display the results 2 - (list) To display a list of selected items from the main results The feature I am trying to implement involves adding a save ...

"Encountering an error message stating "Cannot access SpreadsheetApp.getUi() within this context" when attempting to execute the

I've encountered an issue while trying to access the UI object in Apps Script. The code I'm using is something I've used before without any problems, but now I'm getting an error message that says "Cannot Call the .getUI()" method from ...

Utilizing the PHP function to return a href attribute value

I'm relatively inexperienced with php, so I'm unsure of its capabilities; My goal is to invoke a php function within an href tag and utilize the output as the tag itself.. For instance, consider the following code: HTML <a href= 'tele.p ...

Troubles encountered during the development of Nextjs/Javascript application

I encountered the following errors while developing my application. I am unsure of the reason behind this issue. I created a fetch request in a separate function and attempted to call this fetch function (which is structured as a custom react hook) within ...

Establishing a bidirectional binding directive attribute within an AngularJS HTML structure

I'm new to AngularJs and I've encountered a problem that might be due to my lack of understanding about directives, controllers, and isolated scopes. I'm trying to figure out how to set a directive attribute to true/false in the html and kee ...

Google Chart Fails to Display

I am encountering an issue while attempting to integrate a Google chart into my project. The page fails to load, rendering a blank screen. Initially, the page displays correctly for a brief moment after loading and then suddenly turns blank, becoming unres ...

Is there a problem with the alignment of

<s:form id="inputThresholdForm" name="inputThresholdForm" theme="simple"> <table border="0" class="display-table" cellspacing="2" cellpadding="2" height="100%" width="100%"> <tr> <td colspan= ...

Discover the secrets of flying to customized coordinates stored in variables using Leaflet.js

I'm currently working on a fire location tracking website and I'm facing an issue with leaflet.js. As a newcomer to Leaflet, any assistance would be greatly appreciated! I have a script that successfully retrieves the id of a specific row from a ...

Exploring ways to store session data in Next.js 13 with Supabase for seamless persistence

Encountering an issue with next-auth. Upon logging in, the result shows ({error: 'SessionRequired', status: 200, ok: true, url: null}), despite having an active session. The console also displays this error message, which I believe may be related ...

Reload the Node.js webpage

Is there a method to automatically refresh a Node.js page following a socket.io event? var messageDynamic = "Initial status"; app.get("/", function(request, response) { response.setHeader('Content-Type', 'text/plain'); respons ...

Share the name of the Quasar component with the Vue 3 render function

I'm struggling to dynamically create a Vue 3 app with different components specified by name, such as "div", "button", or Quasar's "q-btn". When I try to pass the latter to Vue's render function Vue.h, I encounter difficulties. <html> ...

Can someone explain why the index call is not reaching the "/" route in Node.js?

When I access the server by going to http://localhost:3000, it displays my index file but does not route to the get function in index.js. I am currently stuck at this point. Below is my app.js file: var express = require('express'); var path = ...

AngularJS Routing misinterprets hash href from jQuery UI Datepicker

This issue is a result of my own oversight. I neglected to properly initialize the model for the datepicker, causing jQuery UI to prevent the navigation event from firing. If you're encountering this same problem, chances are there's another mist ...

What is the best way to access my backend API on a web hosting platform?

To successfully send information from a contact form through an email, I need to access my backend API. My app is deployed on a webhost called Kinghost and I have two URLs provided: the first one is the generic mywebaddr.com:port-number, and the second one ...

The date format adjustments vary depending on the web browser being used

I have a JavaScript function that displays the date in the browser, but the format changes depending on the browser. For example, when I open my project in Chrome, the format is 4/30/2015, but when I open it in IE, it's displayed as 30 April, 2015. Ho ...

Using JavaScript to toggle the visibility of grids depending on the radio button choice and then triggering this action by clicking on the search button

As a newcomer to AngularJS development, I am encountering some challenges while attempting to implement the following scenario. Any suggestions or guidance would be greatly appreciated. I aim to showcase either one or two Angular UI grids based on the rad ...