-3

I was been asked in an interview to code for the following scenario.

var ele = [2,5,4,8,4,9].second();

If the above statement is written in javascript it ele should contain second highest element from that array. In this case it should contain 8.

how do you write the code for this? I assume we will have to write a function second()

but how do we call make sure it takes the array as that parameter?

Please help me with this. Thank You in advance.

masterfly
  • 861
  • 4
  • 11
  • 24

2 Answers2

2

That should get you started

Array.prototype.second = function() {
  var biggest = -Infinity;
  var second = -Infinity;
  for (var i = 0; i < this.length; ++i) {
    if (this[i] > biggest) {
      second = biggest;
      biggest = this[i];
    } else if (this[i] < biggest && this[i] > second) {
      second = this[i];
    }
  }
  return second;
};

You should include error handling and there's plenty of room to optimize this solution.

manonthemat
  • 6,101
  • 1
  • 24
  • 49
1

Add a method to the Prototype of the Array Object.

Array.prototype.second = function() {
  // Your logic here
}
Sushanth --
  • 55,259
  • 9
  • 66
  • 105