Just for the sake of brevity, but not improved performance:
let [second, max] = array.sort().slice(-2)
I might be misunderstanding the docs (developer.mozilla.org/en-US/docs/W...), but it looks like there would be an issue with this implementation. When a callback function isn't passed to the sort method, all the non-undefined array elements are converted to strings and compared to another.
const array = [ 10000, 100, 1000, 10, 1, 11, 123, 45, 8900, 2 ];
// -> array = [ 1, 10, 100, 1000, 10000, 11, 123, 2, 45, 8900 ];
This means that second would point to 45 and max would point to 8900 even though 10,000 exists in the array.
Sure good point:
const [second, max] = array.sort((a,b)=>a-b).slice(-2)
Daaamn that’s slick. 👌🏾👌🏾👌🏾
Yeah but I bet yours is faster :)
We're a place where coders share, stay up-to-date and grow their careers.
We strive for transparency and don't collect excess data.