const arr = [23, 54, 9, 87, 34, 14];
arr.sort((a, b) => b - a);
const result = arr[arr.length - 1];
console.log(result);
Output:
9
- Generally arr.sort() method gives the output as [ 14, 23, 34, 54, 87, 9 ]. Because
sort()treats elements as strings and sorts them lexicographically (like words in a dictionary). - arr.sort((a, b) => b – a) sorts numbers correctly in descending order as [ 87, 54, 34, 23, 14, 9 ]. This method compares by taking two arguments as a and b, 1). If b-a > 0, then b should come before a. 2) If b-a < 0, then b should come after a. 3) If a-b=0, then order should be unchanged.
- From the array [ 87, 54, 34, 23, 14, 9 ], Final output is arr[arr.length – 1] = arr[5] = 9.