How do I get the second largest element from an array in javascript

The most straightforward implementation, without modifying the original array, is to iterate and track the biggest and next biggest:

function nextBiggest(arr) {
  let max = -Infinity, result = -Infinity;

  for (const value of arr) {
    const nr = Number(value)

    if (nr > max) {
      [result, max] = [max, nr] // save previous max
    } else if (nr < max && nr > result) {
      result = nr; // new second biggest
    }
  }

  return result;
}

const arr = ['20','120','111','215','54','78'];
console.log(nextBiggest(arr));

Variations

The behaviour of returning -Infinity if there’s no next maximum value distinct from the maximum value in a non-empty array can be modified at the end of the function, depending on the requirements.

Same as maximum

return result == -Infinity ? max : result;

For an empty array, this will return -Infinity as before, but would otherwise return the same value as the maximum if no next distinct maximum is found.

Return null

return result == -Infinity ? null : result;

Same as above, but the return value of null is more indicative of the nonexistence of a next distinct maximum.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)