Looking to arrange an object by the value of a nested object in Typescript/Angular?

I'm currently developing an Angular 9 application focused on covid-19 cases, and I need to arrange my objects by the value of nested objects.

Here is the dataset that I want to organize alphabetically based on the 'state' field values: state: Kerala, state: Haryana;

{
  "history": [
    {
      "day": "2020-03-14",
      "total": {
        "confirmed": 84
      },
      "statewise": [
        {
          "state": "Kerala",
          "confirmed": 19
        },
        {
          "state": "Assam",
          "confirmed": 14
        }
      ]
    },


    {
      "day": "2020-03-15",
      "total": {
        "confirmed": 104
      },
      "statewise": [
        {
          "state": "Kerala",
          "confirmed": 119
        },
        {
          "state": "Assam",
          "confirmed": 114
        }
      ]
    }
  ]
}


So, after sorting, I expect my data to be like this:

Sorted Data

{
  "history": [
    {
      "day": "2020-03-14",
      "total": {
        "confirmed": 84
      },
      "statewise": [
        {
          "state": "Assam",
          "confirmed": 14
        },
        {
          "state": "Kerala",
          "confirmed": 19
        }
      ]
    },
    {
      "day": "2020-03-15",
      "total": {
        "confirmed": 104
      },
      "statewise": [
        {
          "state": "Assam",
          "confirmed": 114
        },
        {
          "state": "Kerala",
          "confirmed": 119
        }
      ]
    }
  ]
}

You can access my API data through this link: API data API data link. I've spent two days trying to implement solutions similar to this suggested on Stack Overflow answer, but I'm still unsure about the next steps. Any assistance would be greatly appreciated.

Answer №1

Check out the code snippet below for a helpful solution:

this.postService.getDetails().subscribe(
  response => {
    let sortedData= response.data.history
      .sort(function(a, b) {
        return new Date(b.date) - new Date(a.date);
      }); //Sort based on date

      sortedData.forEach(item=>item.statewise.sort(function(a, b) {
        if (a.state < b.state) {
          return -1;
        }
        if (a.state > b.state) {
          return 1;
        }
        return 0;
      })); //sort state wise in alphabetical order

    console.log(sortedData);
    this.loading = false;
  },
  error => {
    console.log(error);
    this.loading = false;
  }
);

For a demonstration, you can view the sample demo at the following links:

Sample Demo

Interactive Demo

Make sure to check the console for the sorted data output.

Answer №2

To achieve this, utilize the sort prototype of array.

let data = {
  "records": [
    {
      "day": "2020-03-14",
      "total": {
        "confirmed": 84
      },
      "statewise": [
        {
          "state": "Kerala",
          "confirmed": 19
        },
        {
          "state": "Assam",
          "confirmed": 14
        }
      ]
    },


    {
      "day": "2020-03-15",
      "total": {
        "confirmed": 104
      },
      "statewise": [
        {
          "state": "Kerala",
          "confirmed": 119
        },
        {
          "state": "Assam",
          "confirmed": 114
        }
      ]
    }
  ]
};

const result = {records: []};

result.records = data.records.map(record => {
  record.statewise.sort((a, b) => a.state < b.state ? -1 : 1);
  return record;
});

console.log(result);
.as-console-wrapper {
    min-height: 100% !important;
}

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

Integrating React js with Layout.cshtml: Mastering the Fusion of React Routing and ASP.NET MVC Routing

My current project involves an ASP.NET MVC core application with the View written in cshtml. The routing follows the conventional asp.net mvc routing pattern. However, I've recently implemented a new module using React JS. Now, I'm faced with the ...

React- hiding div with hover effect not functioning as expected

I'm having trouble using the :hover feature in CSS to control the display of one div when hovering over another, it's not functioning as expected. I've successfully implemented this on other elements, but can't seem to get it right in t ...

Creating a PDF file from a series of images

I've implemented a function using the jsPDF library to generate a PDF from a list of images. The main task is to add these images to the PDF document. Here is the code snippet: const { allImgs } = useAppContext() const doc = new jsPDF(); const gener ...

Determine the exposed area of an element with overflowing content

I am looking for a way to determine which text within an element (such as a div or textbox) is currently visible when there is overflow. As the user scrolls, I need to have an updated list of the visible text. I am open to using any elements, but only a ...

Organizing an angular expansion panel

I am currently dealing with an expansion panel that has a lot of content. The layout is quite messy and chaotic, as seen here: https://ibb.co/Y3z9gdf It doesn't look very appealing, so I'm wondering if there is a way to organize it better or ma ...

Validation parameters provided during the Palantir workshop

At our Palantir workshop, we utilize a form to input values that are then added to an Ontology object. Recently, I've been tasked with validating the combination of userId, startdate, and states from the form inputs to check if they already exist or n ...

How to Import External Libraries into Angular 2

I am attempting to import a 3rd party library called synaptic. This library is written in JavaScript and I have a .d.ts file for it. Here are the steps I have taken: npm install synaptic --save npm install @types/synaptic --save I have also added the fol ...

Retrieving data from Firebase query and displaying as an array of results

Currently utilizing the @react-native-firebase wrapper for interaction with Firebase's Firestore. Within my function, some querying to a specific collection is performed, with the expected result being an Array object containing each located document. ...

Is there a way for my HTML file to connect with my CSS and JavaScript files stored in an Amazon S3 Bucket?

My current project involves hosting an HTML file as a website on AWS S3 in order to circumvent the CORS Policy. However, when I uploaded all my files into a new bucket, the HTML file was able to open but without accessing the accompanying CSS and JavaScrip ...

Sharing data between two PHP pages via an AJAX request

On my webpage, specifically on page 1.php, I am saving a variable to an input field text. Name:abc Done. After clicking the 'done' button, the name abc is sent to another page called 2.php via an Ajax request. In 2.php, I am storing the value ...

Discover the outcome of two asynchronous ajax requests using XHR's onprogress event-handler

My current challenge involves seeking out images within an ajax request response and extracting the src URL for utilization in another ajax request. I am aiming to monitor the loading progress of each image and display the resulting progress in a designat ...

Click handler that transmits data to a server using ajax

I have been tasked with creating a website using HTML, CSS, and JavaScript that includes three buttons. When clicked, these buttons will send codes such as "10," "01," and "11" to a C++ program. The C++ program will then respond and perform a function base ...

Utilizing React JS to dynamically incorporate form values into objects

I have an array of objects where I need to add a key value State : const [row, setRow] = useState([{ nameofthework: "", schedulerefNo: "", unitprice: "", qty: "", uom: "", gst: "", total: "& ...

Error: Trying to access 'MaterialModule' before it has been initialized results in an uncaught ReferenceError

I have been working on a form for a personal project and attempted to implement a phone number input using this example: . However, after trying to integrate it into my project, I encountered an error. Even after removing the phone number input code, the e ...

Downloading multiple files on both iOS and Android devices

Is there a way to download assets (mp3/jpeg) in an Asynchronous manner? I have over 200 files in each case and the process is taking too long. Are there any techniques to speed up the download process on both iOS and Android? ...

Exploring Angular2's ability to interpret directive templates using the ng-container

Recently delving into angular2, I ventured into creating dynamic forms and generating fields by following the guide provided in this URL. The result was as expected. The dynamic form component renders each field one by one using ng-container, like shown b ...

Ways to clear dropdown selection in Vue based on a specific condition?

I am currently developing a dropdown menu for selecting visit status options, which include "pending," "canceled," "rejected," and "approved." In the case of an approved visit status, I would like the dropdown selection to only display the options for "can ...

The render props on the child component are not appearing on the screen as expected

Recently diving into React Native, I created a stateless component designed to iterate through props that contain objects with arrays of tags. The goal was to extract and display a single tag from each array item. (Refer to the console log in the screensh ...

Is it possible to transform a ReadonlyArray<any> into a standard mutable array []?

At times, when working with Angular functions and callbacks, they may return a ReadonlyArray. However, I prefer using arrays in the traditional way and don't want to use immutable structures like those in Redux. So, what is the best way to convert a ...

Retrieve every potential option of a dropdown menu

One of my tasks involves working with a select field that has various values: africa europe america asia oceania Whenever a value is selected, I aim to apply a specific CSS class to a particular div, with the name of the CSS class matching the selected v ...