How can you sort an array based on a shared object property using Angular.js?

I've been grappling with this issue for a while now. My app receives data about individuals in JSON format:

"people": [
      {
        "name": "Ivan",
        "city": "Moscow",
        "country": "Russia"
      },
      {
        "name": "John",
        "city": "Seattle",
        "country": "United States"
      },
      {
        "name": "Michael",
        "city": "Seattle",
        "country": "United States"
      }
    ]

My goal is to categorize them into groups based on their city, and display the options in dropdown <ul>s. For example, if a user selects "Seattle", only John and Michael should be displayed within the <li> elements.

Is there any efficient way to accomplish this task?

Answer №1

app.controller('BarCtrl', function($scope) {
   $scope.users = [
      {
        "name": "Alice",
        "city": "Paris",
        "country": "France"
      },
      {
        "name": "Bob",
        "city": "London",
        "country": "United Kingdom"
      },
      {
        "name": "Eva",
        "city": "Berlin",
        "country": "Germany"
      }
    ];
});

You can easily filter it using the following method:

<div ng-repeat="user in users | filter:{ city: 'London' }">

If you want to have a dynamic search functionality:

<div ng-app="demo" ng-controller="BarCtrl"><input type="text" ng-model="search.city" >
  <ul>
     <li ng-repeat = "user in users | filter: search"> {{user.name}</li>
  </ul>
</div>

Here is a working example for reference.

Note that by specifying search.city as the ng-model, you are filtering based on the city field specifically instead of the entire object.

Answer №2

To achieve grouping, you can utilize the angular-filter library. Modify your view code as shown below:

<ul ng-repeat="(key, value) in people | groupBy: 'city'">
  City: {{ key }}
  <li ng-repeat="person in value">
    person: {{ person.name }} 
  </li>
</ul> 

You can check out the working example on Plunker.

Answer №3

You can use a filter in the select option to limit the user's selection to one city retrieved from the server. Check out this example on JSFiddle.

app.js:

angular.module('myApp', [])
.controller('FooCtrl', function($scope) {
    $scope.people = [
    {
        "name": "Ivan",
        "city": "Moscow",
        "country": "Russia"
    },
    {
        "name": "John",
        "city": "Seattle",
        "country": "United States"
   },
   {
       "name": "Michael",
       "city": "Seattle",
       "country": "United States"
   }
];
})
.filter('unique', function() {
    return function(input, key) {
        var unique = {};
        var uniqueList = [];
        for(var i = 0; i < input.length; i++){
            if(typeof unique[input[i][key]] == "undefined"){
                unique[input[i][key]] = "";
                uniqueList.push(input[i]);
            }
        }
        return uniqueList;
    };
});

html:

<div ng-app="myApp">
    <div ng-controller="FooCtrl">
        <select name="city" ng-model="selectedCity" data-ng-options="person.city as person.city for person in people | unique:'city'"><option data-ng-disabled='true' value="">Select City</option>
        </select>

        <table class="table">
            <thead>
                <tr>
                    <th>Name</th>
                    <th>City</th>
                    <th>Country</th>
                </tr>
            </thead>
            <tbody>
                <tr ng-repeat="person in people | filter: {city: selectedCity}">
                    <td>{{person.name}}</td>
                    <td>{{person.city}}</td>
                    <td>{{person.country}}</td>
                </tr>
            </tbody>
        </table>
    </div>
</div>

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

Can you explain the TypeScript type for the queryKey in React Query?

Currently utilizing react query in conjunction with typescript. What should be the type of arguments passed to the function? export const useIsTokenValid = () => { const { data: token } = useQuery<string | null>(['token'], getToken, { r ...

Is there a way to parse a JSON file and present its data in a TableView using JavaFX?

This particular concept is causing me some difficulty. I possess a local JSON file labeled customers.json, which houses information on 1000 customers. "Customers": [{ "id": 1, "gender": "female", "fi ...

I'm curious about how I can selectively utilize vuex-persistedstate with Nuxt for certain stores only

Check out this library: https://github.com/robinvdvleuten/vuex-persistedstate. I have customized the provided plugin file for Nuxt. import createPersistedState from 'vuex-persistedstate' export default ({ store }) => { createPersistedState ...

How can I easily make ajax requests in FLOW3?

Currently, I am immersed in a FLOW3 project and must say that the experience has been quite enjoyable so far. Despite encountering challenges with the lackluster documentation, working with FLOW3 has been rewarding. However, I have hit a roadblock: I nee ...

When a webpage reload triggers a 404 error, my website's iframe with the source "videoUrl | sanitize" will display

I am attempting to retrieve a videoUrl from a database and set it to the iframe [attr.src] in order to display a YouTube video. It is imperative that the data originates from the database, as there are limitations preventing us from directly uploading and ...

Transforming rows into a JSON key/value pair in PostgreSQL is an effective way to organize

In my dataset, I have a simple table with columns labeled Key_1, Key_2, and Value. Each row contains different combinations of Key_1 and Key_2 values. My goal is to transform the rows from this table into a JSON structure that looks like this: { "my ...

Is there a way to make the React component automatically refresh upon clicking the search button?

Just starting out with React and JavaScript, I decided to experiment with accessing a public API. Here is the function I created: import { useState } from "react"; import CountrySWR from "./CountrySWR"; export default function SearchFo ...

When the JS function 'postMessage()' is invoked on an HTML object tag, what specific action does it perform?

Not too long ago, I found myself on a quest to figure out how to trigger the print function on a PDF that I was displaying in Adobe AIR. With a bit of guidance from a helpful individual and by utilizing postMessage, I successfully tackled this issue: // H ...

Adjusting the viewer.js script

In order to view my pdf files using Mozilla's pdfjs plugin, I currently pass a query parameter to viewer.html like this: http://localhost/MyProject/viewer.html/?file=file.pdf Although this method works fine for me, I have a unique requirement for my ...

The art of rotating PDF files and various image formats

Looking for a way to rotate PDF and image files displayed on an HTML page using jQuery. I attempted: adding a CSS class - without success. Here is an example code snippet: .rotate90 { webkit-transform: rotate(90deg); moz-transform: rotate(90de ...

AngularJS validation for mandatory fields is malfunctioning

I made some changes to an angularjs demo starter code and now I'm facing issues with the required field functionality. Even though I can prevent empty submissions, the "required field" error message still appears after a successful submission. Can any ...

Leverage the greater than operator within an AngularJS controller

This is the data stored in my controller: $scope.data = [{ "F": "1,26,000" }]; $scope.data2 = [{ "F": "26,000" }]; Now I want to implement an if-else condition using this data: if (Number($scope.d ...

Tips for dynamically coloring table cells in Spotfire based on their values

Creating Dynamic Table with HTML After successfully creating a cross table in Spotfire, I now aim to replicate the same table in HTML within a text area. I managed to add values using calculated values, but I'm stuck on how to dynamically set the bac ...

Effective methods for importing components in VueJS 2.0

As a newcomer to VueJs, I have a question regarding the best practice for importing components in a Vue Template Project. I currently have some components that are used in multiple views. After downloading an admin template, I noticed that the samples alwa ...

Is it possible to dynamically add an id or class to an element using document.createElement in JavaScript?

As a beginner in the world of JavaScript, I understand that the code structure I have used here may not be ideal for real-world applications. However, I am using it to practice my understanding of for loops and fetching JSON data. My main query is whether ...

Why does it seem like only one div is being added?

I am facing an issue with dynamically appending multiple div elements. Despite my efforts, only one div element is showing up on the browser when I try to test the code. I have searched for similar problems but could not find any solutions. Any assistanc ...

differences between using form's get method and sending an angular $http.get request

When trying to make a GET request to a specific URL from my Angular frontend to an ExpressJS backend, I encountered some interesting behavior. In the frontend code snippet below: <li> <a ng-click="givequiz()">GiveQuiz</a> </l ...

Refresh the page using a promise in Angular after a delay of 3 seconds

Currently, I am working on enhancing the functionality of the login page. In case a user enters an incorrect login and password combination, my goal is to have the page automatically reload after 3 seconds. Despite my best efforts, I have encountered chall ...

Leveraging $routeProvider alongside $stateProvider

Initially, I utilized $routeProvider in the following manner and it delivered the desired outcome. angular.module('angularProject', ['angularProject.filters', 'angularProject.services', 'angularProject.directives', ...

Guide to successfully navigating to a webpage using page.link when the link does not have an id, but is designated by a

This is my current code snippet: async function main(){ for(int=0;int<50;int++){ const allLinks = await getLinks(); //console.log(allLinks); const browser = await puppeteer.launch({ headless: true }); const page = await browser.newPa ...