Arranging a two-dimensional array within AngularJS based on specified filter criteria

Struggling to sort a nested 2D Array using AngularJS filters? I could use some help with this complex task. Any assistance would be greatly appreciated. Thank you!

I currently have a 2D Array and need guidance on how to sort it within an ng-repeat loop.

Here is the code snippet from the template file...

<ul>
  <span ng-repeat="list in lists">

    <li ng-repeat="list_ in list.list1 | orderBy:'name'">{{list_.name}}</li>
  </span>
</ul>

And here is the corresponding JavaScript code...

$scope.lists = [
{
  no : 1,
  list1 : [{
  name : 'A'
},
{
  name : 'M'
}]},
{
  no : 2,
  list1 : [{
  name : 'B'
}]},
{
  no : 5,
  list1 : [{
  name : 'Z'
}]},
{
  no : 3,
  list1 : [{
  name : 'X'
},
{
  name : 'T'
}]}
]

For further reference, please check out the plunker here.

Answer №1

To achieve this, you can flatten the array so that all inner objects are at the same level using a custom filter

Example:

  <body ng-app="myApp" ng-controller="myCon">
    <ul>
      <span ng-repeat="list in lists | flatten | orderBy:'+name'">

        <li>{{list.name}}</li>
      </span>
    </ul>
  </body>

Custom Filter Function:

app.filter('flatten', function(){
  return function(array){
    var flattenArray = [];
    angular.forEach(array, function(value, index){
      angular.forEach(value.list1, function(val, index){
        flattenArray.push(val);
      })
    })
    return flattenArray;
  }
})

View Demo on Plunkr

Answer №2

When it comes to sorting a nested Array array using an angularjs filter, you might already be on the right track without even realizing it. I've taken the liberty of expanding your data to provide a clearer picture of what's going on:

http://plnkr.co/edit/8SjuLc?p=preview

javascript

var app = angular.module("myApp", []);
app.controller("myCon", myConFun);
myConFun.$inject = ['$scope'];

function myConFun($scope) {
  $scope.lists = [{
      no: 1,
      list1: [{
        name: 'Z'
      }, {
        name: 'X'
      }, {
        name: 'Y'
      }, {
        name: 'A'
      }, {
        name: 'M'
      }, {
        name: 'C'
      }, {
        name: 'B'
      }]
    }, {
      no: 2,
      list1: [{
        name: 'B'
      }]
    }, {
      no: 5,
      list1: [{
        name: 'Z'
      }]
    }, {
      no: 3,
      list1: [{
        name: 'X'
      }, {
        name: 'T'
      }]
    }

  ]
}

html

<ul>
  <span ng-repeat="list in lists">
    <li ng-repeat="sublist in list.list1 | orderBy:'name'">
      {{sublist.name}}
    </li>
    ----------
  </span>
</ul>

output:

https://i.sstatic.net/tU3Yh.png

If this doesn't align with your desired outcome, feel free to provide more details for further assistance.

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

Encountering a Problem Combining Angular Js with Dot Net Nuke 7

After creating a custom user-defined controller and adding a module in dnn7 (with resources for the custom controller), I created a page in dnn7 to access my newly created Module. However, when I tried accessing it, only my HTML Page was displayed. This me ...

Exploring the concept of next middle-ware within the realm of Express.js and Sail.js controllers

Currently, I am utilizing sails.js framework which is constructed on top of express.js. Within my routes.js file, I have defined a route as shown below: '/account/login': { controller : 'Session', action : 'l ...

The challenge of PHP's HTTP_REFERER

I am experiencing an issue with http_referer. In my setup, I have two files: index.php and index.html. The index.php file contains a form that, upon submission, includes information like the http_referer. On the other hand, the index.html file runs an aja ...

What is the best way to decrease the size of the text in the header as the user scrolls down?

I have a fixed header with a large text. I would like the text to decrease in size as someone scrolls down, and return to its original size when the scroll is at the top. The CSS applied when scrolling down should be: font-size: 15px; padding-left: 1 ...

Modifying HTML elements in real-time using AngularJS

Looking for a way to display all posts from the database using AngularJS? You're in luck! I'm currently implementing an 'edit-post' directive to provide users with the ability to edit each post they see. Here's a snippet of the lin ...

Which one is best to use: angular.js $scope.$broadcast, $scope.$emit, or $rootScope.$broadcast?

I'm currently in the process of developing a search directive that I want multiple other directives in my application to be able to listen for changes in the search text. My main focus right now is to grasp the distinction between broadcasting and em ...

javascript mysql and php clash when it comes to loading

I am encountering an issue where I cannot fetch data from my phpMyAdmin database using php code when loading the map api that utilizes javascript. Currently, only the map javascript is being loaded. I have valuable data stored in my database and any assis ...

Angularjs regex filter: applying regular expressions to filter data

I've created a regex pattern to match URLs like this: /^(https?:\/\/)?([\da-z\.-]+)\.([a-z\.]{2,6})([\/\w \.-]*)*\/?$/ Now, I need to incorporate this regex into a filter that will specifically extra ...

Creating an array with user-selected objects in IONIC 3

I've been attempting to separate the selected array provided by the user, but unfortunately, I'm having trouble isolating the individual elements. They are all just jumbled together. My goal is to organize it in a format similar to the image lin ...

Securing your Angular application with user authentication and route guarding ensures

In the process of developing an Angular single-page application (SPA) front-end that interacts with a GraphQL endpoint, I encountered a challenge. Upon user login, I store the token in local storage and update the authentication state in my AuthService com ...

Adjust the position of the background when hovering with the mouse to create a right

Currently, I am implementing a background perspective change with the use of mousemove. However, an issue arises with the right margin of the image after moving it. Everything looks fine initially. Any suggestions on how to prevent this problem? https:/ ...

Move a div smoothly to fill the entire screen starting from its current position

I am looking to make a div expand to full screen upon being clicked, similar to the functionality demonstrated in this Fiddle js link here My goal is to animate the expansion from its current position. When I click on the box, I want it to grow as if expa ...

When using selenium with python, the function excecute_script('return variable') may not technically return variables, even though the variable does exist

My attempt to retrieve a variable from javascript code using selenium is encountering difficulties. Despite the presence of the variable (confirmed by inspecting the source code before executing the script), the command driver.execute_script('return v ...

Displaying API response array object in React application

Currently, I am attempting to retrieve information from an API, parse the response content, and then display it in a loop. However, I have encountered a warning message: webpackHotDevClient.js:138 ./src/App.js Line 20: Expected an assignment or function ...

Changing an array into an object in JavaScript without rearranging the keys

I have a collection { 1: {id: 1, first: 1, last: 5} 2: {id: 2, first: 6, last: 10} 3: {id: 3, first: 11, last: 15} } My goal is to reverse the order of items without rearranging the keys so that it looks like this: { 1: {id: 3, first: 11, last: 15} 2: { ...

How a JavaScript function handles the scope of a for loop index

Here's some Javascript code I'm working with: func1() { for(i = 2; i < 5; i ++) { console.log(i); func2(i); } } func2(x) { for(i = 100; i < 200; i ++) { do something } } I've noticed that when runni ...

Issues with Autofocus in AngularJs on Firefox

Check out this straightforward directive to set autofocus: app.directive('autoFocus', function($timeout) { return { restrict: 'AC', link: function(_scope, _element) { $timeout(function(){ ...

Angular JS response has a property of `$resolved` with a value of false

I am in the process of setting up an Angular JS application that will interact with a Django REST API. My goal is to display an HTML list of classrooms. Here is the template I have created: <body> <div ng-app="schoolApp" ng-controller="sc ...

JavaScript failing to trigger autoClose functionality in Bootstrap dropdown

I tried implementing this code to toggle a bootstrap 5 dropdown, but the autoClose feature didn't work as expected. const dropdown = new bootstrap.Dropdown(document.querySelector('.dropdown-menu'), { autoClose: true }) dropdown.toggle() ...

Steps for accessing documents stored in Sharepoint Document library folders

I have a unique setup in my document library: two folders are automatically created based on the year when files are uploaded. Now, I need to retrieve files from multiple folders using JavaScript... Here is my function for uploading a file and creating a ...