0

Got this array:

$scope.items = [
    {
        itemId: "1.1.1"
    },
   {
        itemId: "1.1.10"
    },
    {
        itemId: "1.1.2"
    },

  ]

I want to sort it by each number seperated by dot.

So the expected output is:

$scope.items = [
    {
        itemId: "1.1.1"
    },
    {
        itemId: "1.1.2"
    },
    {
        itemId: "1.1.10"
    }
  ]

Is this possible to do with the default angular js orderBy?

Link to Fiddle

2
  • 3
    I'm confused, the fiddle you've posted is producing your expected output. Also I'd expect 1.1.2 to come before 1.1.10 Commented May 19, 2017 at 14:31
  • @George. Oops, misstake by me. Updated question, Commented May 19, 2017 at 14:41

1 Answer 1

6

You can use Array.prototype.sort

The sort function sorts the array by using unicode code points, but you can pass your own custom compare function to match your sorting needs, the custom compare function takes in two values and compares them, and places them as per the value returned.

   $scope.items.sort(
    function(a,b){

       /*creates an integer array 
       of all numbers in the dot separated string.*/

       let a_array = a.split('.').map(v => parseInt(v)); 
       let b_array = b.split('.').map(v => parseInt(v));

       /*sorts for each digit, 
       move to next digit 
       if and only if the current digits are not equal*/
       if(a_array[0] != b_array[0])
           return a_array[0] - b_array[0];

       if(a_array[1] != b_array[1])
           return a_array[1] - b_array[1];

       if(a_array[2] != b_array[2])
           return a_array[2] - b_array[2];
    }); 

If you want to reverse the direction of sorting, just reverse the positions of a_array and b_Array in each return statement.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.