Home How to sort string numbers which consist of 3 point?
Reply: 2

How to sort string numbers which consist of 3 point?

K. Talha
1#
K. Talha Published in 2018-01-12 15:37:52Z

I have an array which consists of String numbers which consist of 3 point such as "1.452", "11.3.2","12".

For example if I sort this array

$scope.myArray=["11","14.2","9.2.1","5.6.3","0.9","6.7.2","2","1"];

I want to see this array like so

0.9,

1,

2,

5.6.3,

6.7.2,

9.2.1,

11,

14.2

I want to sort these values in descending order. How can I do this with AngularJS ?

Thank you in advance.

Aleksey Solovey
2#
Aleksey Solovey Reply to 2018-01-12 16:06:41Z

It's not pretty, but I think it works:

var myArray = ["11", "14.2", "9.2.1", "5.6.3", "0.9", "6.7.2", "2", "1"];

function compare(a, b) {
  let aa = a.split(".");
  let bb = b.split(".");
  for (let i = 0; i < aa.length; i++) {
    if (parseInt(aa[i]) > parseInt(bb[i])) {
      return 1;
    } else if (parseInt(aa[i]) < parseInt(bb[i])) {
      return -1;
    }
  }
  return -1;
}

myArray = myArray.sort(function(a, b) {
  return compare(a, b)
})

console.log(myArray);

Taras Polovyi
3#
Taras Polovyi Reply to 2018-01-12 16:11:06Z

So all you need is to write your custom comparator for Array.prototype.sort() function. Let's look at the example below (I'll try to explain it in the comments)

const compareValues = (a, b) => {
  // for each element which we compare we need to split it using '.' to get comparable integers
  const aNumbers = a.split('.');
  const bNumbers = b.split('.');

  // then we start a look over the received arrays
  for (let i = 0; i < aNumbers.length || i < bNumbers.length; i++) {
  
    // here we take a current element. If we doesn't exist we consider it as 0
    let currentA = parseInt(aNumbers[i]) || 0;
    let currentB = parseInt(bNumbers[i]) || 0;
    
    
    if (currentA === currentB) {
    
      // if the numbers are equal, we go to the next pair of items
      continue;
      
    } else {
    
      // otherwise we return the difference between them, which says to sort() function which one is bigger
      return currentA - currentB;
    }
  }
  
  // if nothing was returned from the above for statement all numbers are equal
  return 0;
};

// here's the array, that you want to sort
const arr = ["11","14.2","9.2.1","5.6.3","0.9","6.7.2","2","1"];

// and just call the sort function with our comparator.
const sortedArr = arr.sort(compareValues);

You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.344961 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO