javascript – Sort a list by the second number after a dot-ThrowExceptions

Exception or error:

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?

How to solve:

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);

Answer´╝Ü

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);

Leave a Reply

Your email address will not be published. Required fields are marked *