Arranging numbers in JavaScript lists

        empList = [
        { "Account": "AAA - 0029", "Available": "$100" },
        { "Account": "BBB- 0146", "Available": "200" },
        { "Account": "AAA - 1812", "Available": "300"},
        { "Account": "CCC- 2019", "Available": "400"},
        { "Account": "FYC- 3810", "Available": "500"},
        { "Account": "HHH- 5210", "Available": "600"},
        ]

My list of accounts needs to be sorted based on the numbers in the Account property, either ascending or descending. I've attempted various methods without success. The "-" is used as a delimiter to split "AAA - 0029".

Answer №1

angular.module('app', [])
.controller('MyController', ['$scope', function($scope) {
    $scope.empList = [
        { "Account": "AAA - 0029", "Available": "$100" },
        { "Account": "BBB- 0146", "Available": "200" },
        { "Account": "AAA - 1812", "Available": "300"},
        { "Account": "CCC- 2019", "Available": "400"},
        { "Account": "FYC- 3810", "Available": "500"},
        { "Account": "HHH- 5210", "Available": "600"},
    ];

    $scope.sorted = $scope.empList.sort((a, b) => a.Account.match(/\d+/) - b.Account.match(/\d+/));    
}]);
<script src="//code.angularjs.org/snapshot/angular.min.js"></script>

<div ng-app='app' ng-controller='MyController'>
  <h3>Sorted using ng-repeat:</h3>
  <input type='button' value='{{"Sort by " + (reverse ? "ascending" : "descending")}}' ng-click='reverse=!reverse'/>
  <ul >
     <li ng-attr-temp='{{item.temp = item.Account.match("\\d+")}}' ng-repeat='item in empList | orderBy: "temp": reverse'>{{item.Account}} : {{item.Available}}</li>
  </ul>
  
  <h3>Static sorting through sort function:</h3>
  {{sorted}}
</div>

Answer №2

Give this code a try - I split the string using " " and sorted the numbers accordingly.

var  empList = [
        { "Account": "AAA - 0029", "Available": "$100" },
        { "Account": "CCC - 2019", "Available": "400"},
         { "Account": "BBB - 0146", "Available": "200" },
        { "Account": "FYC - 3810", "Available": "500"},
        { "Account": "AAA - 1812", "Available": "300"},
        { "Account": "HHH - 5210", "Available": "600"},
        ];
        
        
empList.sort(function(a,b){

var aNumber=a.Account.split(" ");
var bNumber=b.Account.split(" ");
return Number(aNumber[aNumber.length-1])-Number(bNumber[bNumber.length-1]);
});

console.log(empList);

Answer №3

This code snippet demonstrates how to sort a list of accounts by their account number

accountList = [
        { "Account": "AAA - 0029", "Available": "$100" },
        { "Account": "BBB- 0146", "Available": "200" },
        { "Account": "AAA - 1812", "Available": "300"},
        { "Account": "CCC- 2019", "Available": "400"},
        { "Account": "FYC- 3810", "Available": "500"},
        { "Account": "HHH- 5210", "Available": "600"},
        ];
        
var sortedAccounts = accountList.sort(function(a,b) {
    var x = a.Account.split('- ')[1];
    var y = b.Account.split('- ')[1];
    return x < y ? -1 : x > y ? 1 : 0;
   });
   
console.log(sortedAccounts);

Answer №4

To extract the last numerical characters from a string, you can utilize a regular expression and employ an object to define the appropriate sorting function. It is recommended to encapsulate the sorting logic within a wrapper for descending order.

function sortBy(key, direction) {
    var sortFunctions = {
            Account: {
                asc: function (a, b) {
                    function getNumericValue(s) { return s.match(/\d+$/)[0]; }
                    return getNumericValue(a[key]) - getNumericValue(b[key]);
                },
            },
            Available: {
                asc: function (a, b) {
                    return a[key] - b[key];
                },
            }
        };
    return sortFunctions[key][direction || 'asc'] || function (a, b) { return sortFunctions[key].asc(b, a); };
}

var data = [{ Account: "AAA - 0029", Available: "1000" }, { Account: "BBB- 0146", Available: "200" }, { Account: "AAA - 1812", Available: "300" }, { Account: "CCC- 2019", Available: "400" }, { Account: "FYC- 3810", Available: "500" }, { Account: "HHH- 5210", Available: "600" }];

data.sort(sortBy('Account'));
console.log(data);

data.sort(sortBy('Account', 'desc'));
console.log(data);

data.sort(sortBy('Available'));
console.log(data);

data.sort(sortBy('Available', 'desc'));
console.log(data);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Answer №5

Here is a way to sort in descending order:

var newArr = empList.sort(function(prev, next) {
    var prevNum = parseInt(prev.Account.split('-')[1]);
    var nextNum = parseInt(next.Account.split('-')[1]);
    
    if (prevNum < nextNum) {
        return 1;
    } else if (prevNum > nextNum) {
        return -1;
    }
    
    return 0;
})

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

Updating website content dynamically using AJAX and URL manipulation without refreshing the page (Node.js)

How can I update the inventory without refreshing the page using both button events and URLs? I want to be able to update to a specific page based on the URL parameter (like /inventory/2) when it is passed to the route. Currently, my AJAX request works but ...

I am attempting to create an API request that is dependent on the outcome of another API request by utilizing a forEach loop. Is there a different approach I could take to achieve the desired

After successfully implementing an API request based on the result of another API request, I am looking for a more efficient method than using forEach for my subsequent API call. Is there a way to achieve this by utilizing Promise.all or any other alternat ...

The process of converting a data:image base64 to a blob is demonstrated in this code snippet

Seeking a way to convert data:image base64 URLs to blob URLs. Below is the original code that generates the base64 URLs: <script> $(window).load(function(){ function readURL() { var $input = $(this); var $newinput = $(this ...

Angular page fails to refresh upon addition or deletion of data

There's a recurring issue with my angular application where the page fails to refresh after data manipulation such as addition, editing, or removal. For example, when I add a new item to a list of subjects, it doesn't show up unless I navigate aw ...

Code for Custom Controllers in Strapi Beta version 3.0

I have encountered some discrepancies in the beta version of Strapi's controllers compared to the previous version. The new version includes multipart/sanitization boilerplate, and I am having trouble integrating my order object and Stripe charge. Be ...

I encountered no response when attempting to trigger an alert using jQuery within the CodeIgniter framework

Jquery/Javascript seem to be causing issues in codeigniter. Here is what I have done so far: In my config.php file, I made the following additions: $config['javascript_location'] = 'libraries/javascript/jquery.js'; $config['javas ...

Can a table with a checkered pattern be created in Ember.js with just Handlebars and ember-composable-helpers?

I'm new to working with Ember.js and I am attempting to create a simple checkered table. In my project, I am utilizing Bootstrap 4, ember-composable-helpers, and Handlebars. Is there anyone who can guide me on achieving this goal WITHOUT the use of ja ...

What seems to be the issue with the useState hook in my React application - is it not functioning as

Currently, I am engrossed in a project where I am crafting a Select component using a newfound design pattern. The execution looks flawless, but there seems to be an issue as the useState function doesn't seem to be functioning properly. As a newcomer ...

Combining object properties from a collection of objects based on matching IDs in JavaScript

I have two arrays of objects that I need to merge together based on matching typeId values. The first array contains information about different states, while the second array contains information about state types. The goal is to combine the properties of ...

The span's onclick function seems to be malfunctioning

I am encountering an issue where the Onclick event is not triggering on a specific tag. Strangely, the same onclick event works perfectly fine when bound to an image element. I am currently developing a follow and unfollow feature using PHP and jQuery. How ...

What is the process for managing items in an array within a separate file?

I am facing an issue where I need to display the 'title' object from an array in the document App.js. Everything works fine when I use an array without any objects: (before) App.js: import React from 'react' import TodoList from ' ...

Trouble with Bootstrap 3's nav-justified feature not displaying correctly upon window expansion

Looking at this Bootstrap example page, I noticed a small issue with the nav-justified navigation. When the window is minimized, it transitions correctly to a mobile version. However, when the window is maximized again, the buttons remain in the mobile for ...

Fetching Data Using Cross-Domain Ajax Request

Seeking assistance with a cross-domain Get request via Ajax. The code for my ajax request is as follows: var currency_path = "http://forex.cbm.gov.mm/api/latest"; $.ajax({ url: currency_path, crossDomain:true, type:"GET", dataTyp ...

Swap out a portion of HTML content with the value from an input using JavaScript

I am currently working on updating a section of the header based on user input from a text field. If a user enters their zip code, the message will dynamically change to: "GREAT NEWS! WE HAVE A LOCATION IN 12345". <h4>GREAT NEWS! WE HAVE A LOCATIO ...

Best practices for effectively dismantling a Paper.js Scope

In my web project, I am utilizing multiple Paper.js canvases by creating a new scope for each of them. Due to the AJAX-driven nature of the site, I need to get rid of unnecessary instances when switching between subpages. Unfortunately, there is no built-i ...

Just starting out with JS/jQuery and having trouble hiding a div as I thought it should (or revealing it incorrectly)

The issue can be observed by visiting . Upon clicking on a location name, a home "button" appears in the bottom left corner. Clicking this home button is supposed to revert back to the original page layout and hide the button. However, as soon as the curso ...

What is the best way to create a list using only distinct elements from an array?

If I have a collection of different colors: Red Blue Blue Green I aim to extract only the unique colors and store them in an array. Subsequently, I plan to incorporate each color from that array into an existing color list. The desired outcome would l ...

In JavaScript, the function is unable to access elements within an iteration of ng-repeat

I am using ng-repeat to display datepickers that are powered by flatpickr. To make this work, a script needs to be added on the page for each input element like so: <script> $('[name="DOB"]').flatpickr({ enableTime: false, dateForm ...

Enhancing socket.io with the incorporation of a variable

I was looking for a way to connect an object named player to various sockets. My initial approach was to simply do socket.prototype.player = whatever; However, no matter what I attempt to prototype, it always returns undefined. Does anyone have a solution ...

Solving SEO issues with jQuery load()

I have developed a modal window that includes links, but unfortunately, search engine crawlers are unable to read and index those links. I am looking for a solution to make sure the crawler can index those links. I have noticed websites using AngularJS li ...