Sorting floating point numbers with AngularJS orderBy

JS:

(function(angular) {
  'use strict';
angular.module('orderByExample', [])
  .controller('ExampleController', ['$scope', function($scope) {
    $scope.friends =
        [{name:'John', phone:'2.5-3.3-7.5', age:10},
         {name:'Mary', phone:'10.5-3.7-9.1', age:19},
         {name:'Mike', phone:'10-21-30', age:21},
         {name:'Adam', phone:'11.1-5-10', age:35},
         {name:'Robert', phone:'1-3-7', age:27},
         {name:'Julie', phone:'9-15-20', age:29}];
    $scope.predicate = 'phone';
    $scope.reverse = true;
    $scope.order = function(predicate) {
      $scope.reverse = ($scope.predicate === predicate) ? !$scope.reverse : false;
      $scope.predicate = predicate;
    };
  }]);
})(window.angular);

HTML:

<table class="friend">
    <tr>        
     <th>
         <button ng-click="order('phone')">Phone Number</button>
         <span class="sortorder" ng-show="predicate === 'phone'" ng-class="{reverse:reverse}"></span>
     </th>         
    </tr>
    <tr ng-repeat="friend in friends | orderBy:predicate">
      <td>{{friend.name}}</td>
      <td>{{friend.phone}}</td>
      <td>{{friend.age}}</td>
    </tr>
  </table>

Result:

Number

  • 1-3-7
  • 9-15-20
  • 10-21-30
  • 11.1-5-10
  • 2.5-3.3-7.5
  • 10.5-3.7-9.1

However, I would like the result to be:

Number

  • 1-3-7
  • 2.5-3.3-7.5
  • 9-15-20
  • 10-21-30
  • 10.5-3.7-9.1
  • 11.1-5-10

My preference is to sort based on phone numbers only. http://plnkr.co/edit/JI8bJ54C3ARurK5w1hFU?p=preview

Answer №1

Looking at your example, it seems that you are already manipulating the phoneNumber by sorting it:

.map(function(friend) {
  // This code removes all non-digits from the phone number
  friend.phoneNumber = Number(friend.phone.replace(/[^\d]/g, ''));
  return friend;
})

If you prefer to keep the original phoneNumber as is, you can simply use map() and apply parseFloat():

.map(function(friend) {
  // This code converts the first part of the friend's phone number to a floating point number
  friend.phoneNumber = parseFloat(friend.phone);
  return friend;
})

Example Link

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

The $OnChange function fails to activate when passing an object by reference

Hi there, I've encountered a problem in my code that I'd like some help with. In my example, I have two components: Parent Component and Child Component. Both components share a field called rules. The Parent Component passes the rules field to ...

Internet Explorer 11 Ajax problem

Once again, Internet Explorer is causing some issues. I have a file called validation.php where the values from a text box are sent for validation. The text box value is read and then a result indicates whether it is valid or not. This functionality work ...

Are there any methods available to adjust the size of a View component in react-native?

My react-native application includes a View that contains several components. The layout displays perfectly on iPhone 6 and 5 models, but on an iPhone 4s, the bottom of one component is being clipped slightly. I'm aware of scaling base64 icons, but I ...

AngularJS: How to open a link in a new tab without including the base URL

I need to open a URL in a new tab. This is what I am currently doing: $scope.portal.jdURL = 'www.google.com'; $scope.openURL = function() { if($scope.portal.jdURL != '') { window.open($scope.portal.jdURL, '_b ...

Inconsistently, Android WebView fails to register touch inputs

I am facing an issue with my Android Web Application that is installed on a Tablet (LGV700 - 4.4.2) dedicated for this purpose and powered 24/7. This application acts as a wrapper to a web application and includes some additional features, all loaded from ...

Could spell-checking be achieved by utilizing Redis as the dictionary in conjunction with AngularJS?

I recently added a search feature to my website that queries my database (or redis) to retrieve results based on user input. The data being searched is comprised of names rather than common dictionary terms. As a result, I am unable to rely on the built-in ...

Disable the javascript link on small devices

I currently have a javascript link (Trustwave) on my desktop website theme that I need to deactivate when viewed on mobile devices: Located in footer.tpl: <div style="position:absolute; margin-left:100px; margin-top:50px"> <script type="text/j ...

Sort the list by a designated value within each item in the list

Is there a way to sort my unordered list based on a specific value within each list item? I am generating my list using a loop. Here is an example of my looped list item. The <?php echo $nyslutdatum; ?> value is the one I want my list to be ordered ...

Leveraging jQuery's element objects and the :contains selector allows for powerful

I need to search for a link that contains the word 'gathered'. Although I understand how to do it logically, I am having trouble writing the jQuery syntax for the selector: if (index === 3) { var $link = $('#rest').find('.tr ...

The concept of position() is often mistaken for a function

I am currently developing a slider and have included the code below: $(document).ready(function() { // MAKE SLIDER WIDTH EQUAL TO ALL SLIDES WIDTH var totalWidth = 0; $('.slide').each(function() { totalWidth = totalWi ...

Prerender is running independently of the dynamic page title and meta tags rendering process

As part of a POC, I was integrating prerender.io with an angular-node application for SEO purposes. My application can be found HERE. The good news is that all three links are being crawled successfully, as confirmed by receiving a 200 OK status for all li ...

The functionality of ng-show becomes compromised when used in conjunction with ng-animate

Once the animate module is activated, the ng-show functionality seems to stop working. Even though the default value for the ng-show expression is set to false, the element is still displayed and the ng-hide class is not being applied. However, if I deac ...

Exploring Angularjs: Retrieving the value of a selected optgroup

When using my application, I need to extract the selected optgroup value from a dropdown menu. Here is the sample code: HTML: <select ng-model='theModel' ng-change="display(theModel)" > <optgroup ng-repeat='group in collectio ...

What is the best way to layer four images in a 2x2 grid over another image using CSS as the background

I am attempting to place 4 images of the same size on a 5th image defined as the background. Currently, it looks like this: It works perfectly when the height is fixed, but in my case, the height may vary causing this issue: This problem isn't surp ...

Tips for managing blur events to execute personalized logic within Formik

I am currently delving into the world of React/Next.js, Formik, and Yup. My goal is to make an API call to the database upon blurring out of an input field. This call will fetch some data, perform database-level validation, and populate the next input fiel ...

Is it considered secure to replace an object within an array when working with Angular bindings?

In my Angular JS project, I have incorporated a form with a reset function. Whenever I begin editing an item on the form, the setPrimarySelectionEditEntry function is invoked. The primarySelectionEntry variable contains the object bound to the controls. ...

Struggling with certain aspects while learning Nodejs and ES6 technologies

Below is an example of using the ES6 method.call() method that is causing an error var obj = { name: "Hello ES6 call", greet: function(somedata) { this.somedata = somedata console.log(this.somedata) ...

Several directories for viewing in Node.js with Express

I have been researching different solutions, but I am still unsure about how to effectively integrate Express with multiple view folders. Imagine an Express application divided into distinct parts, each organized in its own subfolder: app +partA + ...

The ng-repeat directive fails to automatically refresh itself when a new item is added via a dialog box

As a beginner in AngularJs, I am currently working on CRUD Operations using $http and ASP.NET MVC. Here is what I have done so far: I utilize ng-repeat to display a list of "Terms". There is a button that triggers a dialog box for inserting new "Ter ...

Clear the page refresh value in javascript once the jquery ajax action is completed

Under specific circumstances, a jQuery ajax query is utilized to show a message on the page. By clicking "close" on the message, it will vanish. Additionally, there is JavaScript on the same page that triggers an automatic refresh every 30 seconds. My go ...