Wednesday, April 11, 2018

Array ReOrdering - Sort


        In Javascript , the items are sorted as strings by default. So if you try to sort an array with have integer value, it will return incorrect result. See below example,


let arr = [ 1, 2, 7,15, 18 ];

arr.sort();

alert( arr );  // 1,15,18,2,7(Wrong Result)

The above example returns a wrong result. Because as I said earlier, sorted by string is default.

Remember, internally it will convert as string.

1. Classical Trick


function compareNumeric(a, b) {
  if (a > b) return 1;
  if (a == b) return 0;
  if (a < b) return -1;
}

let arr = [ 1, 2, 15, 7, 19, 54, 87, 43 ];
arr.sort(compareNumeric);
alert(arr);  // 1,2,7,15,19,43,54,87

2. With simple comparison




let arrSort = [ 1, 2, 15, 76, 76, 34, 89, 12 ];

arrSort.sort(function(a, b) { return a - b; }); // Ascending

alert(arrSort);

Note: For descending use b-a.


3. Same with Arrow function




let arrSort = [ 1, 2, 15, 76, 76, 34, 89, 12 ];

arrSort.sort( (a, b) => a - b );

alert(arrSort);


Conclusion:

Here all the example is only for integer array. Suppose If you want to sort an string array, no need to worry about above logic. Simply you can call sort method directly.







No comments:

Post a Comment