-2

I am trying to find out how to sort an array of number by decimal. I am this array

[9, 9.10, 9.2, 9.3, 9.4, 9.5, 9.6, 9.7, 9.8, 9.9]

By using sort 9.1 is before 9.2 but what I neeed is to have 9.1 after 9.9 so the order will be as below: 9, 9.2, 9.3, 9.4, 9.5, 9.6, 9.7, 9.8, 9.9, 9,10

How can I force doing that?

Thanks

Alessandro
  • 67
  • 12

1 Answers1

1

Well you have to work with them as string and not numbers. You need to split them into two parts and do the comparisons based on the parts, not the wholes.

var items = ['9', '9.10', '9.2', '9.3', '9.9', '8', '7', '6'];
items.sort(function(a, b) {
  const partsA = a.split(".");
  const partsB = b.split(".");
  if (partsA[0] === partsB[0]) {
    return partsA[1] === partsB[1] ? 0 : (+partsA[1] || 0) > (+partsB[1] || 0) ? 1 : -1;
  }

  return +partsA[0] > +partsB[0] ? 1 : -1;
});

console.log(items);
epascarello
  • 204,599
  • 20
  • 195
  • 236