Advertisement
Rujoyce18

Array sort .

Oct 26th, 2021
1,069
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. // Array Sort.
  2.  
  3. const fruits = ["Banana", "Orange", "Apple", "Mango"];
  4. const val = fruits.sort(); //sort alphabetically.
  5. console.log(val);
  6. const val1 = fruits.reverse(); // it will reverse elements.not Alphabetically.
  7. console.log(val1);
  8.  
  9. const points = [40,100,1,5,25,10];
  10. console.log(points.sort(function(a,b){
  11.   return a-b;
  12. }));//Ascending sort Numerical Array.
  13.  
  14. // console.log(points.sort(function(a,b){
  15. //   return b-a;
  16. // }));//Descending
  17.  
  18. //function(a, b){return a - b} its a compare function.
  19.  
  20. // const points = [40, 100, 1, 5, 25, 10];
  21. // points.sort(function(a, b){return 0.5 - Math.random()});
  22.  
  23. const min=points[0];
  24. console.log(min);
  25. const max = points[points.length-1];
  26. console.log(max);
  27.  
  28. points.sort(function(a,b){
  29.   return b-a ;
  30. });
  31.  
  32. const max1 = points[0];
  33. console.log(max1);
  34.  
  35. //Math.max.apply
  36. //Math.max.apply(null, [1, 2, 3]) is equivalent to Math.max(1, 2, 3).
  37.  
  38. //Math.min.apply(null, [1, 2, 3]) is equivalent to Math.min(1, 2, 3).
  39.  
  40. const cars = [
  41.   {type:"Volvo", year:2016},
  42.   {type:"Saab", year:2001},
  43.   {type:"BMW", year:2010}
  44. ];
  45.  
  46. cars.sort(function(a, b){return a.year - b.year});
  47. console.log(cars);
  48.  
  49. cars.sort(function(a, b){
  50.   let x = a.type.toLowerCase();
  51.   let y = b.type.toLowerCase();
  52.   if (x < y) {return -1;}
  53.   if (x > y) {return 1;}
  54.   return 0;
  55. });
  56.  
  57. console.log(cars);
  58.  
  59.  
  60.  
  61.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement