What is the method for arranging objects in AngularJS using a custom sorting sequence?

I would like to display an array of object's properties in a custom sorted order. Here is the initial array:

$scope.weekDays = [
            {
                "day" : "TUESDAY",
                "count": 10
            },
            {
                "day" : "MONDAY",
                "count": 20
            },
            {
                "day" : "WEDNESDAY",
                "count": 30
            },
            {
                "day" : "SUNDAY",
                "count": 60
            }];

By default, if we print the days from weekDays, it will appear as TUESDAY, MONDAY, WEDNESDAY, SUNDAY.

However, I want to display them in a specific order: "SUNDAY", "MONDAY", "FRIDAY", "TUESDAY","WEDNESDAY"

To achieve this, I have implemented the following:

        $scope.order = ["SUNDAY", "MONDAY", "FRIDAY", "TUESDAY","WEDNESDAY"];

        $scope.sortedArray = [];

        $scope.sortCustomOrder = function() {
            var index = 0;
            for(var i = 0; i < $scope.order.length; i++) {
                for (var j = 0; j < $scope.weekDays.length; j++) {
                    if($scope.weekDays[j].day==$scope.order[i]) {
                        $scope.sortedArray[index] = $scope.weekDays[j];
                        index++;
                    }
                }
            }
        }; 

After printing $scope.sortedArray, it displays the desired order.

Are there any simpler or more efficient methods in AngularJS to accomplish this?

Answer №1

To easily sort the weekDays array, you can utilize the built-in orderBy filter as shown below:

app.controller('MainCtrl', function($scope, orderByFilter) {

  $scope.weekDays = [{
    "day": "TUESDAY",
    "count": 10
  }, {
    "day": "MONDAY",
    "count": 20
  }, {
    "day": "WEDNESDAY",
    "count": 30
  }, {
    "day": "SUNDAY",
    "count": 60
  }];

  var dateOrders = ["SUNDAY", "MONDAY", "FRIDAY", "TUESDAY", "WEDNESDAY"];

  $scope.Sorted = orderByFilter($scope.weekDays, function(item) {
    return dateOrders.indexOf(item.day);
  });
});

Check out this working example on Plunker: http://plnkr.co/edit/IZfiavmZEpHf4hILdjQs?p=preview

Answer №2

Here is a functional plunker I put together for you:

$scope.daysOfWeek = [
        {
            "id" : 3,
            "day" : "TUESDAY",
            "count": 10
        },
        {
            "id" : 2,
            "day" : "MONDAY",
            "count": 20
        },
        {
            "id" : 4,
            "day" : "WEDNESDAY",
            "count": 30
        },
        {
            "id" : 1,
            "day" : "SUNDAY",
            "count": 60
        }];
$scope.sortedDaysOfWeek = $filter('orderBy')($scope.daysOfWeek, 'id')

Check out the Plunker here!

Answer №3

Whenever I need to perform ordering and filtering operations, my go-to is utilizing an existing library.

I highly suggest checking out this particular one: .

This library simplifies sorting your collection, as shown in the examples below:

var items = [{id: 'a', pos: 5},
    {id: 'd', pos: 2},
    {id: 'b', pos: 4},
    {id: 'c', pos: 3},
    {id: 'e', pos: 1}];

// sortedItemsById = ['e', 'd', 'c', 'b', 'a']
var sortedItemsById = $linq(items)
    .orderBy(function (x) { return x.pos; })
    .select(function (x) { return x.id; })
    .toArray();

// sortedItemsByPos = ['a', 'b', 'c', 'd', 'e']
var sortedItemsByPos = $linq(items)
    .orderBy("x => x.id")
    .select("x => x.id")
    .toArray();

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

Error: Rails javascript_include_tag is expecting one argument, but received two (2 for 1)

Every time I try to add my manifest application.js file to the main layout, I keep getting this argument error. <!DOCTYPE html> <html> <head> <%= csrf_meta_tags %> <%= javascript_include_tag "application" %> </head> & ...

Retrieving user input through JavaScript and transmitting information using Ajax

UPDATE: Issue resolved by changing name="demo_name" and similar attributes on my form to id="demo_name". Thanks @Jill I'm attempting to save contact form data into a MySQL database using jquery's ajax feature. I'm new to this, and while it& ...

When the nav-element is clicked, it will load the new content/file.php into the div with the id of "include."

Seeking the most efficient method to load content from a php file into a designated div on my webpage, prioritizing speed, minimal performance requirements, and ease of implementation. Unsure whether it's preferable to utilize php or javascript for t ...

What is the best way to invoke a function that is declared within a React component in a TypeScript class?

export class abc extends React.Component<IProps, IState> { function(name: string) { console.log("I hope to invoke this function"+ name); } render() { return ( <div>Hello</div> ); } } Next, can I cal ...

Decoding user input parameters within a vue module

It seems like I am hitting a wall when it comes to finding solutions for this particular issue. Currently, I have a component that is supposed to retrieve data from a file and display it. My intention is to only pass the filename to the component so that ...

Troubleshooting: AngularJS ng-include not functioning as expected

I attempted to replicate the steps outlined in an Angular template at . Unfortunately, something went wrong and I am unable to identify the issue. Here is what the code looks like: menu.html <div class="container"> <div class="row row-conte ...

Express.js restricts the number of requests to a maximum of 6

I am facing an issue with my Flask server that streams image data using the multipart/x-mixed-replace header. The Express server is set up to connect to the Flask server, receive the image data, and then deliver it to the client also utilizing the multipar ...

Altering the DOM directly within the componentDidMount() lifecycle method without needing to use

In ReactJS, I am facing an issue while trying to manipulate the DOM in the componentDidMount() method. The problem lies in the fact that the DOM is not fully rendered at this point, requiring me to use a setTimeout function, which I find undesirable. Upon ...

Tips for incorporating mapbox.js as a background while keeping html content and Navbar consistently displayed on top

I am currently integrating MapBox.js into a Bootstrap 3 website. The main concept is to utilize a map as the background for a row that occupies the full width of the site, with html-content displayed on top. To ensure MapBox.js remains in the background, I ...

Determine the frequency values and coordinates of the normal distribution curve (X and Y axes)

I have successfully implemented the Histogram chart using react-plotlyjs. The graph is working fine but now I need to draw the normal distribution curve using X and Y axes. While I have the coordinates for the X axis, the Y axis values are automatically ca ...

Change the height of textarea dynamically using jQuery

I am trying to create a comment box similar to Facebook's, where it resizes as text fills it using Expanding Text Areas Made Elegant This is how my view looks: <div class='expandingArea'> <pre><span></span></ ...

Having trouble importing a file in TypeScript?

I needed to utilize a typescript function from another file, but I encountered an issue: I created a file called Module.ts with the following code snippet: export function CustomDirective(): ng.IDirective { var directive: ng.IDirective = <ng.IDire ...

The correct usage of && and || operators in javascript

I've developed a small web application and I'm facing an issue where I want to trigger an alert when the 'enter' key is pressed if there is an empty or space value. Currently, the alert appears not only on hitting 'enter' but ...

SSE and the power of NodeJS through Express

Having trouble receiving SSE events in the browser. This is the server-side code (using Express): app.all('/callme', function(req, res){ res.writeHead(200, { 'Connection': 'keep-alive', 'Content-Type&apo ...

Changing the border of an iframe element using jQuery or Javascript from within the iframe itself

Is it possible to set the border of an iframe to zero from within the iframe itself using JavaScript or jQuery? Any guidance on how this can be achieved would be greatly appreciated. Thank you! ...

Has the binary search operation not been executed?

My attempt to implement the binary search algorithm in my code example is not producing the expected result. I'm unsure of the cause. Can someone please explain it to me? var array = [1, 4, 6, 8, 9, 12, 15, 17, 19, 34, 55, 78, 80]; function binarySe ...

Swagger is unable to locate a user schema when utilizing Yaml files

Hello, I am a beginner using Swagger and trying to create simple endpoint documentation. However, I am facing an issue with my schema type and cannot figure out what's wrong. To start off, I organized my folder structure in the root src directory whe ...

System CSS modules do not work correctly with Reactjs, CRA, TS, and Carco when using Less

Issues have arisen with the CSS module system in my project. Below are snippets from various code files and configurations: react-app-env.d.ts, craco.config.js, CircleButtonWithMessage.module.less, CircleButtonWithMessage.tsx, as described below: //react-a ...

A JavaScript function that smoothly scrolls an element into view while considering any scrollable or positioned parent elements

I needed a function that could smoothly scroll a specific element into view with some intelligent behavior: If the element is a descendant of a scrollable element, I wanted the ancestor to be scrolled instead of the body. If the element is within a posit ...

Encountering a 422 ERROR while attempting to send a POST request

Below is the code snippet I am currently using: const url = new URL("https://api.chec.io/v1/products"); const headers = { "X-Authorization": `${process.env.NEXT_PUBLIC_CHEC_PUBLIC_KEY_SECRET}`, "Accept": "appl ...