Not returning min but returning Max

1551 views javascript
6

I want to know what I am doing wrong, the code below is not returning the minimum number in the array

[ 
   { "id": 1, "phoneNo": "0758709939" },
   { "id": 1, "phoneNo": "0158703431" }
 ]

below is the code I wrote to return the min value

return Array.from(this.phoneNumbers)
   .map((arr) => arr.phoneNo)
   .reduce((prev, curr) => prev > curr ? prev : curr, 0)

Can somebody help me look at it?

answered question

how about you sort the results on basis of phoneNo and then pick the first element of the array?

I think you should invert this condition prev > curr ? prev : curr.

@UmairAbid Bad idea, sorting is O(N log N), an O(N) solution is better

If you wrote the code then you should know about the comparison operators < and > as well as the ternary operator (?;). And you should also know how to fix your problem yourself.

1 Answer

6

You are using wrong condition in the callback given to reduce

return Array.from(this.phoneNumbers)
   .map((arr) => arr.phoneNo)
   .reduce((prev, curr) => Math.min(prev, curr), 0)

posted this

Have an answer?

JD

Please login first before posting an answer.