0

I am new in Javascript.

function find_lowest_and_greatest(number) {
   const lowest = number.sort((a, b) => a - b);    // [1, 2, 3, 4, 5] 
   const greatest = number.sort((a, b) => b - a);  // [5, 4, 3, 2, 1]

   // after ^ line execute lowest value replace with greatest...But why? so lowest = [5, 4, 3, 2, 1] 

   return [lowest[0] , greatest[0]]
 }

 console.log(find_lowest_and_greatest([4, 5, 3, 1, 2])); // [5 , 5]
   // expected > [1,5]

I expected result will be [1,5] But got [5,5]

  • 2
    sort sorts in place and you assign the same object reference. – Nina Scholz Jan 08 '20 at 15:22
  • 4
    you could just sort once and return first and last element – bamtheboozle Jan 08 '20 at 15:22
  • 4
    Your first stop should be [the documentation](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort). Your next stop should be a thorough [search](/search?q=%5Bjs%5D+sort+changes+original). More about searching [here](/help/searching). – T.J. Crowder Jan 08 '20 at 15:23
  • 2
    `[Math.min(...number), Math.max(...number)]` works without the sorting – Shiny Jan 08 '20 at 15:23

0 Answers0