Difference between biggest 2 numbers

PHOTO EMBED

Tue Oct 04 2022 10:02:53 GMT+0000 (Coordinated Universal Time)

Saved by @j_jivan #javascript

/*You have an array of non-negative integers. You need to calculate the difference between the 1st biggest number and the 2nd biggest number of the array.*/

function diffBig2(arr) {
  let maxNum = Math.max(arr[0], arr[1]);
    let secondMax = Math.min(arr[0], arr[1]);
    for (let j = 1,i = 2; i < arr.length; ++i, ++j){
        if (arr[i] > maxNum) {
            secondMax = maxNum;
            maxNum = arr[i];
        } else if (arr[i] > secondMax) {
            secondMax = arr[i];
        }
    }
    return maxNum - secondMax;
}
content_copyCOPY

https://www.codewars.com/kata/55e3f27d5dee52d8dd0000a9/train/javascript