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

Utilizing jQueryUI for rendering tabbed content with JSON data

Although I have the ability to load JSON data that is returned (appearing "as is" in my HTML page), I am facing an issue where the raw JSON data does not disappear. The code I have used is as follows: $( "#tavole" ).tabs({ cache : false, event: "m ...

Looking for a skilled JavaScript expert to help create a script that will automatically redirect the page if the anchor is changed. Any t

Seeking a Javascript expert, In my custom templates, I have used a link as shown below: <a href='http://www.allbloggertricks.com'>Blogging Tips</a> I would like the page to redirect to example.com if the anchor text is changed from ...

Having trouble handling LocalDate Optional deserialization with Jdk8Module?

Currently, I am exploring the use of Optionals in combination with Java 8 and aiming to serialize/deserialize a LocalDate object using Json. To achieve this, I have developed a custom Object Mapper where I included the registration of Jdk8Module: @Bea ...

Bring in a collection of classes of various types from one TypeScript file to another

In my code file exampleA.ts, I define an object as follows: import { ExampleClass } from 'example.ts'; export const dynamicImportations = { ExampleClass }; Later, in another file named exampleB.ts, I import an array that includes class types and ...

Determining the duration since generating a unique objectid in mongodb

I am currently developing an application that offers users the option to reset their passwords. The process is quite straightforward - after entering his email address, the user will receive a link containing the new objectid number. For example: /reset- ...

Cannot access Nextjs Query Parameters props within the componentDidMount() lifecycle method

I have been facing a challenge with my Next.js and React setup for quite some time now. In my Next.js pages, I have dynamic page [postid].js structured as shown below: import Layout from "../../components/layout"; import { useRouter } from "next/router"; ...

Customizing the MUI X Sparkline: Incorporating the percentage symbol at the end of the tooltip data within the MUI Sparklinechart

Presented below is a SparklineChart component imported from MUI X: import * as React from 'react'; import Stack from '@mui/material/Stack'; import Box from '@mui/material/Box'; import { SparkLineChart } from '@mui/x-chart ...

Unable to identify the pdf file using multer in node.js

const multer=require('multer'); var fileStorage = multer.diskStorage({ destination:(req,file,cb)=>{ if (file.mimetype === 'image/jpeg' || file.mimetype === 'image/jpg' || file.mimetype==='image/png') { ...

Error: Attempting to assign a value to the property 'running' of an undefined variable

While working with Nuxt.js, I encountered an issue related to reading the running property of my client object. Here is the HTML code snippet: <b-button v-show="!(projectSelecter(project.ID)).isStarted" //this work just fine variant="success" c ...

An array in a JSON Schema must include a certain specified string value

I have come across several discussions on this topic, yet none seem to directly address the specific issue at hand. The JSON Schema documentation also doesn't provide a clear solution, leaving me uncertain if what I am trying to achieve is even possib ...

Ways of assigning a null value to a key in a JSON body request

I am facing an issue with passing a null value to a key using a POST request in an API. I want to send JSON data where Exp and TeamID should be null, like below: { "ID":162617, "TextKey":"107737", "Exp":nul ...

Retrieving data response post upload with JQuery and an HTML5 Uploader

After uploading an image and receiving a successful post response with the id of the inserted image, how can I insert this response as a data-id attribute within a a tag? Where in the function does this process occur? Here is the function: function img_ ...

[Vue alert]: Component mounting failed due to usage of mixin with a parameter

For the past day, I've been facing difficulties creating a Vue mixin with a parameter. When attempting to do so, I encounter a [Vue warn]: Failed to mount component: template or render function not defined error. Below is my JS file which includes the ...

I am facing unexpected results while trying to search for a string array object using elemMatch in Mongoose

I am encountering an issue that I can't seem to resolve. I need to utilize a query search to match the data of one job with user data, but I'm facing some obstacles. The primary challenge is within my query search for the job where the data looks ...

What is the best approach for manipulating live data in localStorage using ReactJS?

I am working on creating a page that dynamically renders data from localStorage in real-time. My goal is to have the UI update instantly when I delete data from localStorage. Currently, my code does not reflect changes in real-time; I have to manually rel ...

What is the best way to insert an object at a particular position within an array containing numerous nested objects?

This is the given Object: [ { "id": "1709408412689", "name": "WB1", "children": [ { "id": "1709408412690", "n ...

Discover the significance of a data attribute's value for effective comparisons

I have a loop that generates random numbers and positions to create 4 answer choices for users. Now, I am trying to determine the value of the clicked button and compare it to the position of the correct answer. However, whenever I try to do this, it retu ...

What is the reason the child component is not being displayed?

The code within the APP.js component looks like this: import React from "react"; import Exam from "./exam.js"; export default function App() { return ( <Exam> <h1>hashemi</h1> </Exam> ); } Similarly, the ...

Passing parameters to JavaScript onload event from PHP

Looking for help with integrating date data from PHP into a JavaScript countdown function. I have extracted the date from a database using PHP, but struggling to pass it correctly to the JavaScript function. My attempt so far: <body onload="countIt(< ...