Arranging Objects in an Array by their IDs using AngularJS ng-repeat

I am looking to sort the output of an ng-repeat displaying objects based on their specific "id" property. The order in which I want them to appear is stored in an array, so I created a custom filter like this:

ng-repeat="line in dataObject|objectIdFilter:orderByArray"
:

.filter('objectIdFilter', [function() {
    return function(inputObjet, orderArray) {
        var result = [];
        angular.forEach(orderArray, function(value) {
          result.push(inputObjet[value]);
        });
        console.log(result);
        return result;
    }
}])

Here is a basic example controller that includes the objects and the order id in an array:

.controller('MainCtrl', ['$scope', function($scope) {

  $scope.dataObject = {
    1: {username:'user1'},
    10: {username:'user10'},
    20: {username:'user20'},
    500: {username:'user500'}
  };

  $scope.orderByArray = [20,10,1,500];

}])

With the corresponding HTML code:

<div ng-app="myApp">
  <div ng-controller="MainCtrl">
      <div ng-repeat="line in dataObject|objectIdFilter:orderByArray">{{line.username}}</div>
  </div>
</div>

Jsfiddle: https://jsfiddle.net/infnadanada/tLrx4uro/

So...

  • Everything is functioning correctly, but I am unsure if there is another method to sort the ng-repeat as I did without resorting to a custom filter.

  • Additionally, if you check the browser console on the Jsfiddle link provided, you may notice that my custom filter appears to be returning the result twice and I am uncertain as to why.

PS: English is not my first language :D

Thank you!

Answer №1

Here is an alternative method to filter your data within the controller without using the filter function in Angular. This can help avoid calling the filter twice.

$scope.dataObject = {
    1: {username:'user1'},
    10: {username:'user10'},
    20: {username:'user20'},
    500: {username:'user500'}
  };
  $scope.orderByArray = [20,10,1,500];
   $scope.result = [];
  angular.forEach($scope.orderByArray, function(value) {
      $scope.result.push($scope.dataObject[value]);
  });
}]);

Incorporating it into the template:

<div ng-app="myApp">
  <div ng-controller="MainCtrl">
      <div ng-repeat="line in result">{{line.username}}</div>
  </div>
</div>

Answer №2

Another approach is to loop through the map using the following code snippet: https://jsfiddle.net/johndoe/n7jLQz9p/1/

$scope.data = {
    1: {name:'John'},
    5: {name:'Jane'},
    10: {name:'Sam'},
    25: {name:'Alice'}
  };
  $scope.order = [10,5,1,25];
  $scope.sortedData = $scope.order.map(function(key){
      return $scope.data[key];
  });

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

How can I display the value of a radio button that has been chosen?

Would you mind sharing how to display the selected value of a radio button? I attempted it this way, but unfortunately, it did not work. You can view my code at this link. <mat-radio-group [(ngModel)]="favoriteName"> <mat-radio-button *ngFor="l ...

Upon initialization of the API, an Angular $resource is invoked, leading to the retrieval of empty return values

In my quest to create a simple web-based RPG game, I have set up a Java server that offers a REST API for a basic HTML5 application. This application features a service that displays quests organized by category and allows users to view detailed informatio ...

Safari 15.6.1 does not support background video playback in Next.js

Currently using Safari version 15.6.1 for a small website project, I have encountered an issue where the video appears frozen with an arrow in the middle. Oddly enough, this problem only occurs on Safari as both Chrome and Firefox display the code correctl ...

What is the method for determining the word/caret location in Google Docs?

If you're unfamiliar with how the Google Docs editor operates, here's a concise explanation: Unlike traditional text editors, Google Docs does not have a visible editable textarea or contentEditable elements. Google Docs detects keydown/press/u ...

Is there a way to adjust the pivot point of a cone scale in three.js?

I am trying to resize a cone that is generated using THREE.CylinderGeometry. My goal is to make it longer and have it grow in the direction of the negative z-axis, but I've noticed that currently it's growing in both negative and positive directi ...

How to set up 'ng serve' command in Angular to automatically open a private browsing window?

I am looking for a way to open my project in an Incognito Mode browser without storing any cache. Is there a specific Angular CLI flag that can be included in the ng serve -o command or in the Angular CLI configuration file to enable opening a browser in ...

Display a message indicating no data is available if the specified text is not found within the div

In the code snippet below, there is an input element followed by a div containing multiple child elements: <input type="text" onkeyup="filter()" id="filter_data"> <div id="body"> <div class="child"> Text 1 </div> <div class ...

JavaScript button click changes the selected row's color in a DataTable

I am looking to dynamically change the color of a row in my Datatable when a specific button is clicked. Here is the HTML code snippet for the rows: <tr role="row" class="odd"></tr> <tr role="row" class="even selected"></tr> & ...

Switching component upon button click in ReactJS

After clicking the button, I want to change the component displayed on the screen. I have created a function called changeComp() within my component's class. However, when I click the button, it doesn't route to the wallet-connect component as ex ...

Error: dbg variable is not defined in AngularJS

I'm currently in the process of learning angularjs by following a tutorial from this source Take a look at my index.jsp below - <!doctype html> <html lang="en" ng-app="phoneCatApp"> <head> <title>Angular Example</title> ...

Guide to showcasing information interactively using ant design tables

My proficiency in JavaScript is not the best, but I am currently working on building a frontend using React. I have a table that I obtained from ant.design, and I am attempting to populate this table with data from my database. However, I am encountering d ...

Gatsby: Endless rendering loop triggered by context update

My goal is to update the context every time a Gatsby page finishes loading. The approach I took was to provide the context to all pages, and then update it once the page loads using useEffect to ensure it only happens during component mounting. Unfortuna ...

My task is to automate the PDF document in Internet Explorer

Performing PDF tasks is something new to me. Whenever I click on the view link, the PDF document opens up and I have to save it to verify. Unfortunately, there is no download option available for me. https://i.sstatic.net/Dz5lB.png When I click on view P ...

Is setTimeout trustworthy in Node.js environment?

My task requires me to execute multiple "setTimeouts" for 60 seconds each. Essentially, I am creating a new entry in the database and after 60 seconds, I need to verify if the database record has been modified. I prefer not to set up a complex "job queue" ...

What is the best way to include a string in an Ajax GET request as a query parameter without it being encoded?

I've encountered an issue while trying to pass a list of subject IDs as query params in an Ajax get-request. The API expects the subjectId param to be either a single number or a string of numbers separated by commas. I have made sure that what I am s ...

Implementing ng-if with asynchronous functions: A step-by-step guide

The objective here is to display an image in a template only if the ratio of its dimensions is greater than 2. <img class="main-img" ng-if="showImage($index)" ng-src="{{item.img}}"> Implementation: $scope.showImage = function(index) { var img ...

Retrieve the content of a text field with jQuery

Check out this block of HTML: <div class="sub-middle-column"> <div class="div-header">Grandsire <a "#", class="table-control-focus sub-header-table-focus" id="table-control-focus-t" >abc</a> <ul class="table-controls h ...

Prevent clients from navigating the block by using AngularJS when they enter a URL in the

Is there a way to prevent navigation when the user types /pricing in the address bar, and only allow navigation when $location.path("/pricing") is triggered? when("/pricing", { templateUrl: "app/components/Pricing/pricing.html", }) I'm l ...

How do I make the message "document.getElementById(...) is null" become true?

When running my code, only two of the document.getElementById calls (ctx1 and ctx2) successfully get values while the others (such as ctx3) do not. How can I ensure that all elements retrieve their values without receiving an error message? Below is a snip ...

Accessing the Vuex store from external JavaScript files is not allowed

The structure of my application can be found in the following link Architecture of my app For my specific use case, I am looking to utilize getters in the Axios interceptor (/../src/app/shared/services/http-client/http-client.js) to include the authoriza ...