Sorting after grouping in AngularJS is a breeze

After using lodash.js groupBy to organize my collection, the order is correct when I log it with console.debug. However, when I try to display it in the UI using ng-repeat, the ordering gets messed up.

    var list = [{id:1,categoryId:1,name:test1},
                {id:2,categoryId:2,name:test2},
                {id:3,categoryId:12,name:test12}]

    vm.myList= _.groupBy(list,function (j) { return j.categoryId; });

    console.debug(vm.myList) // this shows the correct ordering!!!

Despite my efforts with orderBy in ng-repeat, the display order is incorrect:

<div ng-repeat="(categoryId, details) in vm.myList| orderBy: 'categoryId'>
        {{ categoryId }}
</div>

The current output is:

1
12
2

I want it to display as:

1
2
12

I have tried sorting by parsing the categoryId but it doesn't work:

<div ng-repeat="(categoryId, details) in vm.myList| orderBy: 'parseInt(categoryId)'>
            {{ categoryId }}
    </div>

UPDATE! This issue does not occur in Angular 1.4.x. Unfortunately, we are using an older version, Angular 1.3.x.

Answer №1

Initially, the orderBy filter only works with arrays, so if you attempt to pass an object to it, the passed object will be returned as is.

Furthermore, when using ngRepeat

It is important to note that the JavaScript specification does not specify the order of keys returned for an object. (To address this issue in Angular 1.3, the ngRepeat directive used to sort the keys alphabetically.)

In version 1.4, the alphabetical sorting was removed.

If you prefer to maintain a specific order, the recommended solution is to convert your object into an array that is sorted according to your desired order before passing it to ngRepeat. This can be achieved using a filter like toArrayFilter

To resolve your problem, simply convert your grouped object into an array and sort it accordingly.

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

The v-for directive is displaying my list in a single row with multiple columns instead of in a single column with multiple rows

Can someone please assist in rendering my list as shown below: A B C The current rendering looks like this: 1: A 2: B 3: C Below is the code snippet: To-Do List: <input type="text" class = "todo" placeholder = "Next Item" v-on:keyup.enter="add ...

Is there anything resembling 'Spread' and 'allSettled' in node with Q?

In my experience with Q, I have found the Q.allSettled function to be incredibly useful for handling arrays of promises, especially when needing to manage failure cases without using a specific fail handler. Currently, I find myself needing to utilize the ...

Refreshing canvas with new javascript content following an ajax request

Issue: When using ajax driven pagination to load canvas based portfolio items, script tags are not within the canvas tags. Attempted Solution: Tried placing script tags before canvas tags, but scripts still did not load (seems to be a loading script issue ...

Determine whether a specific key exists in the formdata object

Can I check if a key in the formdata object already has a value assigned to it? I am looking for a way to determine if a key has been previously assigned a value. I attempted something like this but did not get the desired outcome data = new FormData(); ...

Unable to receive comment reply through Ajax without refreshing the comment section

I'm facing an issue where I cannot retrieve comment replies via Ajax under comments, even though the replies are successfully saved in the database. Oddly enough, upon refreshing the Index.php page, the replies display correctly. I suspect the problem ...

Capture a snapshot of a Bootstrap modal using JavaScript

var takeScreenShot = function(){ html2canvas(document.body, { onrendered: function(canvas) { var tempcanvas=document.createElement('canvas'); tempcanvas.width=1350; tempcanvas.height=1350; var context=tempcan ...

Make sure that the click event listener is set up on the anchor element so that it also affects its children

Currently, I have implemented a click event listener on my anchor elements. However, the anchors contain a span element within them, and the event listener does not function properly if you click on the span inside the anchor. document.addEventListene ...

The day text function failed to return a value and instead gave back

I am having trouble figuring out where the mistake is in my function below. My goal is to retrieve the day value in string format. function getDayText(date){ var weekday = new Array(7); weekday[0]= "Sunday"; weekday[1] = "Monda ...

What's the best way to implement a conditional header in React?

I am looking to create a conditional display of the Header based on different pages. Specifically, I want the Header to be hidden on the Home page and shown on other pages like posts page, projects page, etc. I have been brainstorming possible solutions f ...

Customize the background color of InfoBox in Google Maps API V3 using a dropdown menu

I'm attempting to dynamically change the background color of an InfoBox by using a Dropdown list (this InfoBox is used to create map labels). I am using google.maps.event.addDomListener, but the values are not returning. Below is my code, can anyone i ...

Encountering an issue with core.js:15723 showing ERROR TypeError: Unable to access property 'toLowerCase' of an undefined value while using Angular 7

Below, I have provided my code which utilizes the lazyLoading Module. Please review my code and identify any errors. Currently facing TypeError: Cannot read property 'toLowerCase' of undefined in Angular 7. Model Class: export class C_data { ...

problem encountered while attempting to transmit data to multer in React

I was attempting to upload an image to the backend using Multer. I have reviewed the backend code multiple times and it appears to be correct. Could there be an issue with my front-end code? Here is a POST code snippet: const response = await fetch(' ...

What steps can I take to stop the browser from refreshing a POST route in Express?

Currently, I am using node along with stripe integration for managing payments. My application includes a /charge route that collects various parameters from the front end and generates a receipt. I am faced with a challenge on how to redirect from a POST ...

What is the best way to identify key presses using Javascript?

Exploring various resources online, I have come across multiple recommendations (such as using window.onkeypress or jQuery) but each option comes with its own set of criticisms. How can the detection of a keypress be achieved in Javascript? ...

Change the spread operator in JavaScript to TypeScript functions

I'm struggling to convert a piece of code from Javascript to Typescript. The main issue lies in converting the spread operator. function calculateCombinations(first, next, ...rest) { if (rest.length) { next = calculateCombinations(next, ...res ...

What strategies can I implement to integrate Cordova with a combination of Meteor and React?

I'm currently struggling to implement a Cordova plugin with Meteor and React. According to the documentation: You should wrap any functionality that relies on a Cordova plugin inside a Meteor.startup() block to ensure that the plugin has been fully ...

When attempting to import my JSX file into page.js, I continue to encounter the error "module not found." How can I troubleshoot and resolve this issue in Visual Studio Code

I recently created a new file called mysec.jsx in the components folder of src. I then used the export function to properly export it. However, when I tried to import this file in page.js using the import function, I encountered an error message that said: ...

Implementing a class addition on focus event using Angular 2

Currently, I am in the process of upgrading an Angular 1 application to Angular 2 and encountering an issue with one of my existing directives. The task at hand is straightforward. When an input field is focused, a class should be added (md-input-focus) a ...

Using HTML and C# to Deliver Emails

I've encountered a challenge with my HTML page that includes a textbox for users to input their email. When the submit button is clicked, an email should be sent to a specific email address defined in the code, and a pop-up box indicating "Email Sent" ...

Angular definitely typed does not convert into JavaScript

After installing TypeScript on my VS2013, I obtained the Angular 1.5 Definitely Typed from the NuGet package manager. Although angular.d.ts and its components do not generate angular.js file, when I create another TypeScript file like file1.ts, the file1. ...