Filtering with multiple attributes in Angular using GroupBy

I have a set of JSON data structured like this:

[
    {
        "id": 1,
        "address": "MG Road",
        "country": INDIA,
        "state": AP,
        "city": VIJ
    },
    {
        "id": 2,
        "address": "Miyapur",
        "country": INDIA,
        "state": TS,
        "city": HYD
    },
    {
        "id": 3,
        "address": "Autonagar",
        "country": INDIA,
        "state": AP,
        "city": VIJ
    },
    {
        "id": 4,
        "address": "Kukatpalli",
        "country": INDIA,
        "state": TS,
        "city": HYD
    },
    {
        "id": 5,
        "address": "Koti",
        "country": INDIA,
        "state": TS,
        "city": HYD
    }
]

My goal is to display the data in the following format:

IND,TS,HYD
     Miyapur, Koti, Kukatpalli
IND,AP,VIJ,
     MG Road, Autonagar

To achieve this, I attempted to use the groupBy filter, but encountered issues in grouping the values.

This is the code I tried:

<div class="location-container">
            <label ng-repeat="(key,value) in locationmodel | groupBy: '[country,state,city]'">{{key}}
            </label>
            <span ng-repeat="location in value">{{location.address}}</span>
      </div>

Unfortunately, the above code did not produce the desired outcome. Any assistance in resolving this issue would be greatly appreciated.

Thank you in advance.

Answer №1

Check out this solution: https://jsfiddle.net/mqt0xjjc/

Here is the code snippet for HTML:

<div ng-app="myApp">
<div  ng-controller="Main">
    <div ng-repeat=" (groupedBy, groupedItems) in locationmodelGrouped">
        <b>{{groupedBy}}</b>
        <li ng-repeat="item in groupedItems">{{item.address}}</li>        
    </div>
</div>
</div>

And here is the JavaScript part:

angular.module('myApp', []).controller( 'Main', 
function($scope) {
    function groupBy(items, groupByAttrs) {
        const retVal = items.reduce(
          function (sum, item) {
            const key = groupByAttrs.map( attr => item[attr]).join(',');
            sum[key] = sum[key] || [];
            sum[key].push(item);
            return sum;
          },
          {}
         );
      return retVal;
    };

    $scope.$watch('locationmodel',
        function () {
        $scope.locationmodelGrouped = groupBy($scope.locationmodel, ['country','state','city'])
      }
   )

$scope.locationmodel = [{
    "id": 1,
    "address": "MG Road",
    "country": 'INDIA',
    "state": 'AP',
    "city": 'VIJ'
},
{
    "id": 2,
    "address": "Miyapur",
    "country": 'INDIA',
    "state": 'TS',
    "city": 'HYD'
},
{
    "id": 3,
    "address": "Autonagar",
    "country": 'INDIA',
    "state": 'AP',
    "city": 'VIJ'
},
{
    "id": 4,
    "address": "Kukatpalli",
    "country": 'INDIA',
    "state": 'TS',
    "city": 'HYD'
},
{
    "id": 5,
    "address": "Koti",
    "country": 'INDIA',
    "state": 'TS',
    "city": 'HYD'
}
];

});

Answer №2

To view the desired output, you can give this code a shot:

<!DOCTYPE html>
<html>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<script>
   var myApp = angular.module('myApp', []);
   myApp.controller('myAppCtrl', function ($scope) {
    var locationmodel = [{
      "id" : 1,
      "address" : "MG Road",
      "country" : "INDIA",
      "state" : "AP",
      "city" : "VIJ"
     }, {
      "id" : 2,
      "address" : "Miyapur",
      "country" : "INDIA",
      "state" : "TS",
      "city" : "HYD"
     }, {
      "id" : 3,
      "address" : "Autonagar",
      "country" : "INDIA",
      "state" : "AP",
      "city" : "VIJ"
     }, {
      "id" : 4,
      "address" : "Kukatpalli",
      "country" : "INDIA",
      "state" : "TS",
      "city" : "HYD"
     }, {
      "id" : 5,
      "address" : "Koti",
      "country" : "INDIA",
      "state" : "TS",
      "city" : "HYD"
     }
    ];
    var resultObj = {};
    for (var i = 0; i < locationmodel.length; i++) {
     if (resultObj[locationmodel[i].country + ',' + locationmodel[i].state + ',' + locationmodel[i].city])
      resultObj[locationmodel[i].country + ',' + locationmodel[i].state + ',' + locationmodel[i].city].address.push(locationmodel[i].address);
     else
      resultObj[locationmodel[i].country + ',' + locationmodel[i].state + ',' + locationmodel[i].city] = {
       address : [locationmodel[i].address]
      };
    }

 $scope.result=resultObj;
   });
</script>
<body ng-app="myApp" ng-controller='myAppCtrl'>
 <div class="location-container" ng-repeat="(key,value) in result">
  <label >{{key}}</label><br>
  <span>{{value.address.join()}}</span>
 </div>
</body>

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

Angular.js can efficiently handle waiting for multiple resource calls and AJAX requests

I'm facing a challenge in my Angular.js application where I need to make three separate resource calls and then use the data together once all the requests are complete. Here are the three calls I need to make: # Retrieve the curriculum $scope.curric ...

JavaScript code to find a date within a specified range

I have developed a script that calculates the number of weeks between two specified dates. It then generates a table where the number of rows equals the number of weeks. The script can be viewed on JSFIDDLE Script: $('#test').click(function ...

update the componentWillMount() function

I am currently exploring the code found at https://github.com/Spyna/react-store/blob/master/src/createStore.js What adjustments do I need to make in order to align with the deprecated componentWillMount lifecycle method? CreateStore const createStore = ...

Using ngFor in Angular 2-5 without the need for a div container wrapping

Using ngFor in a div to display an object containing HTML from an array collection. However, I want the object with the HTML node (HTMLElement) to be displayed without being wrapped in a div as specified by the ngFor Directive. Below is my HTML code snipp ...

Using conditional statements to render content based on a certain condition within a

One of my requirements is to dynamically render a React component in the following manner: parent.ts ... <Parent> <Child/> <Parent> ... child.ts ... return (someBoolean && <Component/>) ... While ...

Exploring the implementation of method decorators that instantiate objects within Typescript

Currently, I have been working on a lambda project and utilizing the lambda-api package for development. As part of this process, I have implemented decorators named Get and Post to facilitate mapping routes within the lambda api object. These decorators e ...

Guide on transferring information from .ejs file to .js file?

When sending data to a .ejs file using the res.render() method, how can we pass the same data to a .js file if that .ejs file includes a .js file in a script tag? // Server file snippet app.get('/student/data_structures/mock_test_1', (req, res) = ...

Whenever Ionic is paired with LokiJS, it consistently results in the error message: "ionic.bundle.js:26794 TypeError: Cannot read property 'insert' of undefined"

Having faced numerous issues with SQLite, I decided to explore LokiJS as an alternative solution for my Ionic app. However, even with LokiJS, I encountered challenges. Currently, I have a simple code that should function smoothly: .controller('Proje ...

Unique Javascript Library Focused on AJAX

Looking for a specific JavaScript library that focuses solely on AJAX functionality, such as a basic XMLHttp wrapper. ...

Discovering the center of an element and implementing a left float

I'm looking for a way to dynamically position the element #ucp_arrow in the middle of a div using float: left. Here is an illustration: https://i.stack.imgur.com/nzvgb.png Currently, I have hard-coded it like this: JAVASCRIPT: $("#a_account").cli ...

Ways to showcase title using ng-repeat

<input type="text" ng-model= "name" title="{{name}}">//this title displays the name that is contained in ng-model Similarly... <select title ="{{item.actionId}}" ng-model="item.actionId"> <option ng-repeat="action in actionList" value="{{ ...

Optimal Placement for FB.Event.subscribe

Here is the code I have implemented on my website for the Facebook Like and Share buttons. The functionality works seamlessly. When I click the Like button, a notification is promptly displayed on my Facebook profile page. Additionally, Facebook automatic ...

Is it a Javascript comparison glitch, or have I overlooked something important?

Recently, I've been working on a JavaScript code that is designed to retrieve data from a server regarding the temperature readings from 2 sensors. The data is stored in a text file where each line includes a date along with 2 values corresponding to ...

The environmental variable remains undefined even after it has been established

I've been experimenting with setting my environment variable in the package.json file so that I can access it in my server.js file. Despite trying NODE_ENV=development, set NODE_ENV=development, cross-env NODE_ENV=development, and export NODE_ENV=deve ...

What is the best way to filter through JSON data in Vue.js?

I'm encountering an issue with my JSON file that I am rendering to a table. I have 11 columns including id, name, and more. I want to search by every column, but the functionality only works for one column. If I try to filter the data multiple times, ...

What could be causing this code to keep looping?

This is my submission for a class project. The task given was: "Create a function that will kickstart the program and name it main(). From the main() function, invoke a function named getValue(). The getValue() function will prompt the user to input a num ...

Are you receiving a response code 500 when making a request to a presigned URL?

I've been encountering an issue with generating presigned URLs for files from my S3 bucket. Although I can successfully read files and obtain a list of file contents, when attempting to create a presigned URL using the following code snippet: reports ...

Failed to convert the value "hello" to an ObjectId (string type) for the _id path in the product model

i am currently using node, express, and mongoose with a local mongodb database. all of my routes are functioning correctly except for the last one /hello, which is giving me this error: { "stringValue": "\"hello\"&qu ...

Black-colored backdrop for Mui modal

Currently working with a mui modal and encountering an issue where the backdrop appears as solid black, despite setting it to be transparent. I attempted to adjust the color to transparent, but the issue persists. ...

Trigger a click event on a nested Angular 13 component to remove a class from its grandparent component

In my Angular 13 project, I am working with 3 components: Child Component : Burger-menu Parent Component : Header Grand-Parent Component : app.component.html Within the burger-menu component, there is a close button. When this button is clicked, I want t ...