-1

I need to sort a list by the second batch number with JavaScript.

This is how it looks like now:

1101.19
1201.17
1301.09

What I need is:

1301.09
1201.17
1101.19

As I am still learning to program I can't figure out the issue. But need it at work.

Can someone help me understand the process of how to do it?

Codebelle
  • 11
  • 3

2 Answers2

1

Sort the array depending on the decimal part. Here is the solution

Sort the array by selecting the decimal part of the number inside the sort function.

You can get the decimal part of any number by taking modulus operation with 0.1. Link.

const arr = [1101.19, 1201.17, 1301.09, 1201.20];
arr.sort((a, b) => {return (a % 1 - b % 1)});
console.log(arr);
Nitheesh
  • 19,238
  • 3
  • 22
  • 49
0

You need to split each element before sort and compare second parts

let array = ["1101.69", "1701.57", "1301.09"];
array.sort((a,b)=>{
  let pair1 = a.split('.');
  let pair2 = b.split('.');
  return ( parseInt(pair1[1]) < parseInt(pair2[1])) ? -1 : 1;
});
console.log(array);
Banzay
  • 9,310
  • 2
  • 27
  • 46