Ordering ng-repeat in AngularJS using a separate arrayDiscover how to easily order your

Imagine I have an array containing keys in a specific order

orderedItems=["apple","banana","orange];

and there is a JSON object that I want to display using ng-repeat but following the sequence specified in the array:

{"fruits":
    {
    "apple":{
        "color":"red",
        "taste":"sweet"
        },
    "banana":{
        "color":"yellow",
        "taste":"creamy"
        }, 
    "orange":{
        "color":"orange",
        "taste":"citrusy"
        }
    }
}

How can I create a filter so that ng-repeat lists the fruits in the exact order as they are mentioned in the array?

<li ng-repeat="item in fruits | customOrder"></li>

Answer №1

If you want to create a custom filter, follow these steps:

View the example on Plunker: http://plnkr.co/edit/fiuuGoGZK7tM5oefKQlS

Here is the code for index.html:

<!DOCTYPE html>
<html ng-app="plunker">

<head>
    <meta charset="utf-8" />
    <title>Filter Example</title>
    <link rel="stylesheet" href="style.css" />
    <script data-require="<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="3e5f50594b525f4c10544d7e0f100c1046">[email protected]</a>" src="http://code.angularjs.org/1.2.15/angular.js" data-semver="1.2.15"></script>
    <script src="app.js"></script>
</head>

<body ng-controller="MainCtrl">
<li ng-repeat="person in people|orderNames:orderedNames track by $index">{{person.hair}}</li>
</body>

</html>

And here is the content of app.js:

var app = angular.module('plunker', []);

app.controller('MainCtrl', function($scope) {
    $scope.people={
        bob:{
            hair:"brown",
            eyes:"blue",
            height:"tall"
        },
        sarah:{
            hair:"blonde",
            eyes:"blue",
            height:"short"
        },
        mike:{
            hair:"red",
            eyes:"blue",
            height:"tall"
        }
    };
    $scope.orderedNames=["mike","bob","sarah"];

});

app.filter("orderNames",function(){
    return function(input,sortBy) {
        var ordered = [];
        for (var key in sortBy) {
            ordered.push(input[sortBy[key]]);
        }

        return ordered;
    };
});

Answer №2

Here's a suggestion you might want to consider

<li ng-repeat="name in orderNames">
    {{people[name]}}
</li>

Answer №3

Using an array as a reference:

Check out this link for more information on arrays

    $scope.persons = {
   bob:{
     name:'bob'
   },
   mike:{
     name: 'mike'
   },
   sarah: {
     name: 'sarah'
   }
 };

 $scope.orderedNames = [$scope.persons.mike, $scope.persons.bob, $scope.persons.sarah];

HTML :

<ul ng-repeat="person in orderedNames">
         <li>{{ person.name }}</li>
       </ul>

Answer №4

when you need to iterate over an array in a different order specified by another array, follow these steps:

Firstly, set up the following code snippet in your controller:

$scope.sortOrder = [1,2,3,4] //or any desired sorting order

Next, in your template, use the following syntax:

| orderByCustom:sortOrder:true/false

The true/false flag determines whether items not present in the sorting array will be displayed at the end or excluded altogether.

Don't forget to implement the custom filter as shown below:

var app = angular.module("app", []).filter("orderByCustom", function () {
            return function (input, sortOrder, includeOrphans) {
                //sorts by specified array and places unsorted items at the end if not in sorting array
                if (!angular.isDefined(input)) { return; }
                var ordered = [];
                var remaining = _.cloneDeep(input);
                angular.forEach(sortOrder, function (orderItem) {
                    if (angular.isDefined(input[orderItem])) {
                        ordered.push(input[orderItem]);
                        delete (remaining[orderItem]);
                    }
                });
                if (includeOrphans) {
                    angular.forEach(remaining, function (remainingItem, key) {
                        ordered.push(input[key]);
                    });
                }
                return ordered;
            };
        });

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

Using jQuery to retrieve the content of a textarea and display it

I need help finding the right way to read and write to a Linux text file using JavaScript, jQuery, and PHP. Specifically, I want to retrieve the value from a textarea (#taFile) with jQuery ($("#taFile").val();) and send it via $.post to a PHP script that w ...

Transforming the shopping cart with redux-saga

Hey there! I've been working on implementing a shopping cart feature using redux-saga. The current code seems to be functioning properly, but I have some concerns about the way I'm handling the cart state. It looks like I might be mutating the ca ...

The error message InvalidCharacterError is displayed when the attempt to create a new element using the 'createElement' method on the 'Document' object fails. This is due to the tag name provided ('/static/media/tab1.fab25bc3.png') not being a valid name

Hey everyone! I'm new to using React and I decided to try cloning Netflix by following a tutorial on YouTube. However, I've encountered an issue with rendering an image in a functional component. The error message I'm receiving is as follow ...

Creating a feature that uses a button press to initiate an Ajax request based on a specific identifier

I'm looking for the most efficient way to structure a page that involves making Ajax calls. My main issue lies in setting up the event binding for when a user clicks a button. I'm struggling to find a method to pass the ID to the function that t ...

The JavaScript-generated form element will not be included in the data submitted through the POST method

While it may appear that this question has been asked before, my specific inquiry seems to be unique as I have not found a similar answer in other threads. Therefore, I am initiating a new discussion. My issue revolves around a form which contains a link ...

Error in Next.js 11: Unable to access property 'canonicalBase' as it is undefined

Encountering an issue after upgrading from Next.js version 10.0.2 to 11.0.1. Since the update, I am unable to initiate a project due to the following error: Cannot read property 'canonicalBase' of undefined In my _app.tsx file, the Next imports ...

Skip nodes in Polymer 1.0 by using ExcludeLocalNames

I recently attempted to transition from Polymer version 0.5 to 1.0 and came across a particular question: Is there a way to exclude certain nodes inside a paper-menu? In the previous version (0.5), you could use the attribute excludedLocalNames to achieve ...

When using Vue.js, the class binding feature may not function properly if it is referencing another data property that has variants

I am currently developing a basic TODO application. Within my index.html file, I have a main div with the id #app. Inside this div, there is another div with the class .todobox where I intend to display different tasks stored in my main.js file. Each task ...

Issue with JavaScript code for Google Maps API not functioning as expected

Can someone help me troubleshoot why my simple Google Maps setup isn't working? Thanks! HTML <script defer src="https://maps.googleapis.com/maps/api/js?key=AIzaSyBy2rXc1YewdnqhPaaEd7H0I4DTV_pc7fo&"> </script> <div id="map"> & ...

Fixing TypeError: Object #<IncomingMessage> has no method 'flash' in ExpressJS version 4.2

Currently, I am utilizing ExpressJS 4.2 and PassportJS for authenticating local users. Everything seems to be working smoothly except for when attempting to display a failureFlash message. Below is my configuration setup, thank you in advance! ==== Necess ...

Exploring React hook functionalities can lead to discovering unexpected issues such as cyclic dependencies on location.hash when

My implementation of a useEffect involves reading the location.hash and adjusting the hash based on certain dependencies. Here is a snippet of how it works: useEffect(() => { const hashAlreadyPresent = () => { const hashArr = history.locati ...

Carrying over additions in arrays using only Javascript

I'd like to implement a basic array addition with carryover. Additionally, I need to display the carryover and result values. For instance: e.g var input = [[0,0,9],[0,9,9]]; var carryover = []; var result = []; Thank you! ...

Add different input strings to an array within the scope when there is a change in the input value (AngularJS)

My goal is to populate an empty array within the scope with strings. The number of elements in this array can vary depending on what the user types in the player count input field. $scope.playerNames = []; To achieve this, I am using a $watch function th ...

What is the best way to eliminate items from an array in a side-scrolling video game?

In my gaming project, I am creating a unique experience where the player needs to collect all the words from a given array. Currently, I am utilizing the shift() method to eliminate elements, as demonstrated in the code snippet below: if ( bX + bird.width ...

Having trouble rendering arrays and objects in Node, Express, and Jade?

//What is currently being passed to the Jade template exports.displayList = function(req, res){ res.render('report', {title: 'Custom Reports', rpts:[{uri:'/reports/allocation', title:'Allocation Report' ...

Emit Observables within deeply nested callback functions

Hey there! I'm currently working on a web app using Angular2/4 and I've encountered an issue with Observables. My goal is to call a function within a component and then have some code executed once that function completes. Here's the releva ...

Experiencing difficulties with Magento operations

Currently facing an issue while attempting to set up Magento on my server. I have transferred all files from another server to mine, but now encountering an error. Could this be related to the symlinks I generated or is it caused by something else? Encoun ...

Angular Functions and Their Application

Just starting out with Angular and facing a challenge with handling downloaded JSON data. I wrote this function: for (var i = 0; i < $scope.Objects.length; i++){ $http.get($scope.Objects[i]["Commit"]).success(function(data) { Commit = data ...

I'm baffled as to why this code isn't functioning properly

My current script seems to be malfunctioning for some reason. I'm using a combination of express, socket.io, jade, and node.js in this setup. Below is the script I am working with: var socket = io.connect(); function addMessage(msg) { var currentDa ...

Running shell commands through child_process in JavaScript

Is there a way to execute shell commands from the browser and display the result on the UI using child_process? I'm having trouble fetching the results from the command line asynchronously. Is there something I'm overlooking here? const exec = ...