Customizing order and limit features in AngularJS

I have a collection of items that I need to organize into separate lists based on priority levels.

items = [
    {'type': 2, 'priority': 1, 'name': 'one'},
    {'type': 1, 'priority': 2, 'name': 'two'},
    {'type': 1, 'priority': 3, 'name': 'three'},
    {'type': 1, 'priority': 4, 'name': 'four'},
    {'type': 1, 'priority': 5, 'name': 'five'},
    {'type': 2, 'priority': 6, 'name': 'six'},
]

Using ng-repeat, I want to sort these items by priority and group them by type. Each list should have a maximum sum of 4 for the type values. The final output should be as follows (sorted by name)

['one', 'two', 'three', 'four']
['five', 'six']

Answer №1

To implement sorting and grouping in JavaScript, leverage the power of Underscorejs as shown below:

var sortedItems = _.chain(items).sortBy('priority').groupBy('type').value();

You can then easily iterate over the new array using ng-repeat directive.

UPDATE: Check out the working example on jsfiddle: http://jsfiddle.net/abcd1234/

Answer №2

Utilizing a specialized Angular filter, you have the ability to easily filter your ng-repeat as demonstrated below or on this jsfiddle.

Instead of utilizing a forEach loop, another option would be to implement a lodash or underscore method (such as groupBy('type').

Angular filters also provide an alternative approach, as showcased in this jsfiddle, eliminating the need for a custom filter.

angular.module('demoApp', [])
    .filter('filterByType', TypeFilter)
    .value('MAX_ITEMS', 4) 
    .controller('mainController', MainController);

function TypeFilter($filter, MAX_ITEMS) {
    return function(input, selectedType) {
        var out = [], count=0,
            ordered = $filter('orderBy')(input, 'priority');
        //console.log("filter start", ordered);
        
        angular.forEach(ordered, function(obj, index) {
            if ( obj.type == selectedType.type && 
                count < MAX_ITEMS ) {
                out.push(obj);
                count++;
            }
        });
        //console.log(out);
        return out;
    }
}

TypeFilter.$inject = ['$filter', 'MAX_ITEMS'];

function MainController() {
    
    this.filterTypes = [
            {type: 1},
            {type: 2}
        ];
    this.type =  this.filterTypes[0];
    this.items = [
        {'type': 2, 'priority': 1, 'name': 'one'},
        {'type': 1, 'priority': 2, 'name': 'two'},
        {'type': 1, 'priority': 3, 'name': 'three'},
        {'type': 1, 'priority': 4, 'name': 'four'},
        {'type': 1, 'priority': 5, 'name': 'five'},
        {'type': 2, 'priority': 6, 'name': 'six'},
    ];
     
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="demoApp" ng-controller="mainController as ctrl">
    Filter by type:
    <select ng-model="ctrl.type" ng-options="opt.type for opt in ctrl.filterTypes"></select>
    <p>selected type: {{ctrl.type.type}}</p>
    <ul>
        <li ng-repeat="item in ctrl.items |filterByType:ctrl.type">
            {{item.name}}
        </li> 
    </ul>
</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

Tips for managing a 64-bit signed integer received from a NextJS backend API

I am currently developing a NextJS application in which one of the backend API routes sends back a JSON object that includes a 64-bit signed integer. // userID represents the 64-bit signed integer res.status(200).json({ id: userId, attributes: userAttribut ...

Fetch a single random profile image from a Facebook user's list of friends using Javascript

I'm currently facing an issue with displaying a random profile picture of the user's friends on Facebook. I attempted to troubleshoot it myself but ended up crashing the login button and now it's not functioning properly. Can someone please ...

The CSS menu dropdown fails to function properly on desktop view when there is longer content present

I attempted to merge two different navigation bars, one sticky and the other responsive. The goal was to combine https://www.w3schools.com/howto/howto_js_navbar_sticky.asp with https://www.w3schools.com/howto/howto_js_responsive_navbar_dropdown.asp Curr ...

Executing a pair of queries within the same table and integrating them within a unified route

How can I efficiently execute two queries on the same table in my project? I have been considering using promises, but my knowledge on them is limited. Even though I've researched about it, I am struggling to implement the correct structure. My main ...

Error: Attempted to access undefined property 'renderMenu' in a promise without handling it

I am looking to generate a dynamic menu based on the JSON data provided below: [ { "teamId": "10000", "teamName": "Laughing Heroes", "superTeamId": "", "createTime": "2017-06-25T06:07:45.000Z", "createUserId": null }, { "team ...

What makes arrays declared as "char word[5] = "hello" flexible in comparison to strings declared as a pointer (char *word = "hello")?

My understanding was that: char word[5] = "hello"; is equivalent to char *word = "hello"; due to the fact that arrays always decay into pointers, right? ...

Tips for migrating an AngularJS application to Angular

My current project involves implementing a basic search function using AngularJS (link). I want to integrate this feature into an existing Angular application. To do this, I created a new Angular app and transferred the view to app.component.html. <hea ...

Rapid processing of JavaScript upon page load

I recently implemented a dark mode feature on my WordPress site. Here are the four modes I included: 1- Automatically based on user's system settings 2- Light mode 3- Semi-lit mode 4- Dark mode The implementation is in place and functioning perf ...

The Jquery flot plugin is failing to plot the graph accurately based on the specified date

I am currently working on plotting a graph using the jquery flot plugin with JSON data. Here is what I need to do: Upon page load, make an AJAX call to receive JSON data from the server. From the received JSON, add 'x' and & ...

When utilizing row.add in AngularJS and jQuery DataTables, the ng-click function may not function as expected

As a newcomer to angularjs, I have successfully implemented the jQuery DataTable directive with angularJS. However, I am encountering an issue when trying to add a JavaScript function to "TR" dynamically using "ng-click", as it does not seem to be recogniz ...

Finding unique data stored in separate JSON files and loading them individually may require using different methods for

I have two JSON files named marker.json and marker.json0 that contain different latitude and longitude coordinates. To load them, I need to rename .json0 to .json (and vice versa), so that the new data from marker.json0 now resides in marker.json. This way ...

The webpage is missing a rendered React component even though it should be displayed

I am facing an issue where a React component is not appearing on the webpage despite being rendered. I have provided the code and screenshots of the components below for reference. Below is the snippet from the "App.jsx" file: function createCard ...

An unexpected error has occurred within React Native, indicating that an object is

It's baffling why I keep receiving the error message: "undefined is not an object (evaluating '_this.props.navigation.navigate')" I am fairly new to react and have tried every possible solution but still cannot resolve this error. Belo ...

Is it possible to utilize the same Context in multiple forms within React?

Is it possible to utilize React Context to store the state of multiple forms, or should each form have its own unique Context? Below is a snippet of code that showcases the use of React Hooks API: In FormContext.js ... import {FormReducer} from './ ...

Issues encountered when trying to install Angular 2 packages through npm in Visual Studio 2015 Update 2

I'm currently trying to integrate the latest angular2 quickstart files into a brand new ASP.NET Core 1.0 Web Application. Running VS2015 Update 2 - with Core 1.0 RC2 already installed To replicate this issue: Start by creating a fresh project usin ...

Regex substitute every instance of the phrase CONTAINED within brackets

I am looking to replace all instances of text within brackets, including the brackets themselves, in a given string. The specific text to be replaced will be stored in a variable in Javascript. Using a simple regex in a replace method won't work due t ...

Tips for creating animations with multiple elements that share the same classes

I am trying to create expandable boxes that can open onclick and close again by clicking on the X. The issue I'm facing is that the close jQuery function isn't working. However, my main concern is how to optimize the code so it doesn't becom ...

Obtaining the Div ID After Clicking on a Link

I'm attempting to fade out a box once the X in that box is clicked. I haven't been able to make it work even after searching on Google. I managed to get it working when clicking the div itself using $(this), but my goal is for it to work when the ...

What sets returning a promise from async or a regular function apart?

I have been pondering whether the async keyword is redundant when simply returning a promise for some time now. Let's take a look at this example: async function thePromise() { const v = await Inner(); return v+1; } async function wrapper() ...

Implementing HTML content inside an el-select component in Vue.js using Element UI

I am working with a dropdown feature that has various options: var Main = { data() { return { drawer: { form: { period: null } }, data : [ { label: "JAN to MAR 2021", value: " ...