Tips on effectively organizing information retrieved from an XML file?

I would like to organize the data in ascending order based on the DATE after making this ajax call

function parseXML(xml){

    var weatherArray = [];
    var weatherElement = xml.getElementsByTagName("forecast")[0];
    weatherArray.queryTime = weatherElement.getAttribute("queryTime");
    weatherArray.queryLocation = weatherElement.getAttribute("queryLocation");
    weatherArray.weatherList = [];


    function sortDates(a,b){
        return parseInt(a.getElementsByTagName("date")[0].childNodes[0].nodeValue) - parseInt(b.getElementsByTagName("date")[0].childNodes[0].nodeValue);
        }
        var weatherElements = weatherElement.getElementsByTagName("weather");
        weatherElements=weatherElements.sort(sortDates);

    for(var i=0; i< weatherElements.length; i++){
        var weather = {};
        weather.year = Number(weatherElements[i].getElementsByTagName("year")[0].childNodes[0].nodeValue);
        weather.month = Number(weatherElements[i].getElementsByTagName("month")[0].childNodes[0].nodeValue);
        weather.date = Number(weatherElements[i].getElementsByTagName("date")[0].childNodes[0].nodeValue);
        weather.dayOfWeek = weatherElements[i].getElementsByTagName("dayOfWeek")[0].childNodes[0].nodeValue;
        weather.overall = weatherElements[i].getElementsByTagName("overall")[0].childNodes[0].nodeValue;
        weather.overallCode = weatherElements[i].getElementsByTagName("overallCode")[0].childNodes[0].nodeValue;
        weather.highest = Number(weatherElements[i].getElementsByTagName("highest")[0].childNodes[0].nodeValue);
        weather.lowest = Number(weatherElements[i].getElementsByTagName("lowest")[0].childNodes[0].nodeValue);
        weatherArray.weatherList.push(weather);
    }
    return weatherArray;
}

Once displayed in the browser, I want the data to be sorted starting from the record with the DATE 26 followed by 27, then 28... There are more repeated data in the XML that I did not show here.

What could be causing my issue?

Answer №1

Behold, a functional solution:

var climateElements = [];
var climateElementsArr = climateElement.getElementsByTagName("climate");

for (var i in climateElementsArr) {
    if (climateElementsArr[i].nodeType == 1) {
        climateElements.push(climateElementsArr[i]);
    }
}

climateElements.sort(s);

The issue resided here:

var climateElements = climateElement.getElementsByTagName("climate");
    climateElements=climateElements.sort(s);

The variable climateElements held an HTMLCollection, making it unsuitable for sorting since it is not a native JavaScript array but rather a collection of HTML elements.

By converting the elements to an array, you can now effectively sort through them as initially intended.

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

When the page is scrolled to 50 pixels, a modal pop-up will appear

I attempted to use cookies to store a value when the user clicks on a popup to close it, ensuring that the popup does not show again once closed. However, I am encountering an issue where the popup continues to open whenever I scroll, even after closing it ...

What's causing ng-show to malfunction in IE11 on AngularJS?

I am experiencing a strange issue with my code - ng-show works perfectly fine on Firefox, but not on IE 11. <div ng-show="isExist" class="panel panel-default"> Here is the relevant code snippet from the controller: $scope.isExist = false; if(user ...

An error occurred due to an unexpected identifier, '_classCallCheck', while the import call was expecting exactly one

Encountering an unexpected identifier '_classCallCheck'. Import call requires precisely one argument. Having trouble with React Native. I have attempted every solution found on the internet, but none proved successful. Is there any way to upgrade ...

Steps for pulling data from the Google Analytics query tool

I'm looking to retrieve my Google Analytics report using an API and save it locally. I've set up a Report in Google Analytics Explore, see attached image: https://i.sstatic.net/lkbKj.jpg From there, I can download the CSV file containing the da ...

Revolutionizing messaging with Vue JS and Firebase

My web application is designed to check if a user has messages in the Firebase database. If messages are found, it retrieves the data from the users who sent those messages from my local database and displays them in a list using a v-for loop. The display ...

Encountering a Laravel Exception in Ajax POST Requests

I am facing an issue with a select box that I use to redirect clients. Before implementing Laravel, my system worked fine, but now I am encountering a problem. $('#parent_products').change(function(){ productid = $(this).val(); ...

The AMP HTML file is unable to load due to the robots.txt file on https://cdn.ampproject.org restricting access

I've been trying to fetch and render my AMP HTML files individually, but they all seem to be encountering the same issue. According to the Search Console report, it says "Googlebot was unable to access all resources for this page. Here's a list: ...

Angular 2: Enhancing Tables

I am looking to create a custom table using Angular 2. Here is the desired layout of the table: https://i.sstatic.net/6Mrtf.png I have a Component that provides me with data export class ResultsComponent implements OnInit { public items: any; ngO ...

The property 'licenses' has incompatible types. The type 'License[]' cannot be assigned to type 'undefined' in the getServerSideProps function while using iron-session

I am encountering an issue with red squiggly lines appearing on the async keyword in my code: Argument of type '({ req, res }: GetServerSidePropsContext<ParsedUrlQuery, PreviewData>) => Promise<{ props: { admin: Admin; licenses?: undefined ...

Access files using the file_get_contents PHP function by utilizing AJAX

I need to use AJAX to retrieve the HTML response from two PHP functions. Below is my code: Home.php <script> $( document ).ready(function(){ var parameter = { "mynumber" : $('#mynumber').val() }; $.ajax({ ...

The raycaster is experiencing issues when used with multiple cameras in the Three.js library

I am currently developing an application similar to the threeJs editor. In this project, I have implemented four different cameras, each with unique names and positions. Here is an example of one of the cameras: cameras['home'] = new THREE.Combi ...

Fetching the exchanged messages between the sender and recipient - utilizing MongoDB, Express, and React for chat functionality

I am dealing with two collections named students and teachers in the mongodb database. The structure of a conversation between a student and a teacher involves arrays of messages within each object, as well as the IDs of the sender and receiver. I am seeki ...

Ways to retrieve information from a specific key

I'm currently facing a challenge accessing specific data objects that are referenced by keys. In this particular scenario, the "applicant" data is nested within an Event object. My goal is to extract this data and create a new object from it. While I ...

What is the importance of always catching errors in a Promise?

In my project, I have implemented the @typescript-eslint/no-floating-promises rule. This rule highlights code like this - functionReturningPromise() .then(retVal => doSomething(retVal)); The rule suggests adding a catch block for the Promise. While ...

Vanilla JavaScript error: Unable to access property

I am working on implementing a header with a logo and navigation that includes a menu toggle link for smaller viewports. My goal is to achieve this using Vanilla JS instead of jQuery. However, when I click on the menu toggle link, I encounter the followin ...

The redirection code is not being executed when calling .pipe() before .subscribe()

My AuthService has the following methods: signUp = (data: SignUp): Observable<AuthResponseData> => { const endpoint = `${env.authBaseUrl}:signUp?key=${env.firebaseKey}`; return this._signInOrSignUp(endpoint, data); }; signIn = (data: SignIn): ...

Submitting a form using AJAX without specifying the form ID when there is a change

I have a unique setup on my page where a table is created with each cell acting as a form. The goal is for these forms to submit when the input value changes (onchange) without refreshing the entire page. An example scenario would be allowing users to ent ...

Is the Browser not Opening when Running npm start with webpack Due to a Peer Dependency Issue with [email protected] and webpack@^4.0.0?

I just started learning JavaScript and decided to explore the webpack-starter project on GitHub (https://github.com/wbkd/webpack-starter). Following the instructions, I cloned the repository and ran npm install in the project folder. Upon encountering a lo ...

Performing a solitary search query across multiple tables and producing a single outcome

I have been working on creating a powerful search feature using AJAX that can find results in 3 separate tables and display them all together in a single table. Currently, I achieve this by making 3 database calls (one for each table), but I am seeking a m ...

Retrieving information within a loop through the utilization of a left join操作。

Presently, I am utilizing a while loop to fetch user comments from a MySQL table and applying a conditional class to the buttons within the comment div. Each comment contains two buttons: thumbsup button thumbsdown button I aim to assign the class name ...