Utilizing Filters in AngularJS to Group and Display Data

I am working with the following object and need to create a filter to group data by ParentCategoryID.

[
{id : 116, Desciption : 'Item1', ParentID : 1, parent : 'Parent1'},
{id : 117, Desciption : 'Item2', ParentID : 2, parent : 'Parent2'},
{id : 118, Desciption : 'Item3', ParentID : 2, parent : 'Parent2'},
{id : 119, Desciption : 'Item4', ParentID : 1, parent : 'Parent1'}
]

The desired outcome is:

Parent1
  Item1
  Item4
Parent2
  Item2
  Item3

The current state of my filter is as follows:

productDetailsApp.filter('groupBy', function() {
    return function(list, group_by) {       
        var filtered = [];
        var prev_item = null;

        angular.forEach(list, function(item) {
            if (prev_item !== null) {
                if (prev_item[group_by] === item[group_by]) {
                    filtered.push(item);
                } 
            }

            prev_item = item;
        });

        console.log(filtered);
        return filtered;
    };

});

And in the HTML :

 <div data-ng-repeat="d in details | groupBy:'ParentID'">
            <h2 >{{d.parent}}</h2>           
            <li>{{d.Desciption}}</li>
  </div>

However, this only displays the last element as prev_item for the first item will always be null:

Parent1
  Item4
Parent2
  Item3

If anyone can provide assistance, I would greatly appreciate it. Thank you.

Answer №1

Instead of the current data arrangement, it would be more semantically logical to organize your information in the following format:

[
    {
        id: 1,
        title: 'Parent 1',
        items: [
            {id: 126, description: 'Item 1'},
            {....}
        ]
    }
]

You can then utilize nested repeats to better reflect the actual scenario and simplify your workflow. If restructuring the data is not feasible or you need assistance with nested ng-repeats, feel free to reach out for alternative solutions.

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

Jquery Banner Fade In animation malfunctioning

I am facing an issue with my banner on various browsers, especially IE 7,8, and possibly 9. When the fade-in effect is applied at the bottom of the banner, the shadows underneath turn black. Is there anyone who can help me resolve this issue? Website: ww ...

Positioning Thumbnails with Jquery Cycle Plugin

Initially, my inquiry is quite similar to a question that was previously posted here. However, the difference lies in the fact that I am utilizing WordPress and the nextgen gallery plugin to handle my images. mygallery/image1.jpg mygallery/image2.jpg and ...

Enhance the functionality of the 'validate as true' function

I have an object that resembles the following $scope.object = { Title: 'A title', Status: 'Open', Responsible: 'John Doe', Author: 'Jane Doe', Description: 'lorem ipsum dolor sit' } My aim now i ...

Access Sharepoint List data using Angular JS

I recently developed an Angular JS application that is supposed to display a list of data from a Share Point list. However, I am encountering difficulties with making a rest API call to my Share Point List as it keeps returning a 403 Forbidden error. Belo ...

Innovative dropdown menu featuring images and informative text snippets

I have a question about creating a menu similar to the one on http://www.resellerclub.com that includes images and text details. Are there any ideas on which technologies were used or if there are any commercial solutions available for this? Thank you. ...

What is the best way to ensure that child elements within a container div are centered when scrolling left and right?

When attempting to handle the 'scroll' event, I noticed that the callback function only records the position of the div as the last position. I am looking for a way to determine if the div is in the center, which is my target. const slide = ...

Using Facebook login with Node.js: A comprehensive guide

Working on a web application with Angular on the frontend and Node.js on the backend. The frontend includes a Facebook login button (js-sdk) to fetch user data via the Graph API. The backend consists of rest APIs that require authentication. I attempted t ...

What is the best way to extract a CSS rule using PHP?

Below is an example of the stylesheet I am currently using: #thing { display: none; } I am looking to retrieve the value of the 'display' property using PHP instead of Javascript. While I know how to do this with Javascript, I would prefer to u ...

Guide on automatically navigating pages using HTML

My dilemma involves two HTML pages: flash.html main.html I am seeking a solution where the flash.html page is loaded first for 5 seconds, after which the main.html page should automatically load. How can I achieve this? I attempted to use setTimeout(fu ...

Using `preventDefault()` will also block any text input from being entered

Note: I am looking for a way to clear the text box using the enter key after typing some text. My apologies for any confusion caused. Update 2: The missing event parameter was causing all the issues. I feel like a failure as a programmer. I am trying to ...

Execute a function once the router-view in the App.vue component has been refreshed following a route alteration triggered by vue-router

Is there a way to trigger a function after the contents in <router-view/> within App.vue have been updated following a route change? I attempted using the updated() lifecycle hook, but the function is not being executed. Interestingly, the function ...

If the first element of the array contains all the letters of the second element, then return true

I attempted to tackle this challenge by creating a loop that iterates through the firstword each time a letter matches with a letter in the secondword. function mutation(arr) { var compare = []; var firstword = arr[0].toLowerCase(); var secondword = ...

Tips for reformatting table row data into multiple rows for mobile screens using ng-repeat in Angular

Just started using Angular JS and I have some data available: var aUsers=[{'name':'sachin','runs':20000},{'name':'dravid','runs':15000},{'name':'ganguly','runs':1800 ...

How to Retrieve the Order Number of an Object in an Array using JavaScript ES6

Curious about JavaScript ES6 and needing assistance! I have a simple question - how can I determine the order number of an object in an array? [ { "pk": 23, "image": "http://localhost:8000/media/users/1/2_27.jpg"}, { "pk": 11, "image": "http://localho ...

Middleware in Express can be executed more than once

I am encountering a frustrating issue where my middlewares are being called multiple times without explanation. Despite having written short and simple code while learning Express and Node, I cannot pinpoint the reason for this behavior. I find it confusin ...

Visualizing JSON data on D3.js graph axis

Below is a snippet of JSON data that I successfully plotted on a d3js graph, using it as the x and y axis: var data = [ { "count": "202", "year": "1590" }, { "count": "215", "year": "1592" }, { "count": "179", "year": "1593" } ]; Now, I am facing a chal ...

Utilizing titanium to develop a functionality that listens for button presses on any area of the screen

I am trying to simplify the action listener for 9 buttons on a screen. Currently, I have individual event handlers set up for each button, which seems inefficient. Is there a way to create an array of buttons and manipulate them collectively? For example ...

How can HTML text be highlighted even when it's behind a transparent div?

In my React application, I am facing an issue with a transparent div that serves as a dropzone for draggable elements. This div covers text and also contains children elements that may have their own text content. <Dropzone> <SomeChild> . ...

Issue with loading templates in multi-level nested states

I have organized my states in the following manner. The first state is abstract, and all second-level states (list, edit, and new) load perfectly. However, my third-level state (passengers) is not loading; it remains stuck on the edit state UI. What could ...

Guide to generating a nested Material-UI style object in React by mapping through an array

I am dealing with some property data that is being passed in a particular format: columns={ [ { name: "Fund Name", width: "40%" }, { name: "Review Date", width: "20%" }, { name: "Company Debt", wid ...