0

How to return max element of a given array using the code structure below?

var array = [100, 0, 50]; 

function max(array) {
  // code
}

Thank You.

Artem Z
  • 565
  • 1
  • 9
  • 19
  • [Try this](https://www.google.co.in/webhp?sourceid=chrome-instant&rlz=1C1CHWA_enIN642IN642&ion=1&espv=2&ie=UTF-8#q=How+to+return+max+element+of+an+array+javascript) – Rayon Sep 17 '15 at 13:34

2 Answers2

0

Try Math.max.apply(Math, array)

var array = [100, 0, 50];

Another solution

function max(array) {
    var max = array[0];
    for (var i = 0; i < array.length-1; i++) {
        max = max > array[i+1] ? max : array[i+1];
    }
    return max;
}
Richard Hamilton
  • 25,478
  • 10
  • 60
  • 87
-1

Use the spread operator (ES2015):

Math.max(...arr)

The spread operator is not yet available in all browsers and runtimes - check the compatibility table.

joews
  • 29,767
  • 10
  • 79
  • 91
  • I don't think it's right to start giving ES2015 suggestions to plain "javascript"-tagged questions without clearly stating it won't work in most places out of the box yet. – Evert Sep 17 '15 at 13:38
  • I've linked Kangax's compatibility table, which will stay up-to-date. – joews Sep 17 '15 at 13:45