Calculating the min/max value from an array in JavaScript

The native min and max functions don’t support arrays as their argument. Instead they take a variable-length argument list of numbers. Sometimes, however, you need to pick the smallest or the biggest number from an array. In this case it’s your responsibility to provide such min/max functions.

For those who can’t wait to copy and paste, scroll down to the third example, that’s what you want.

Example #1

The following snippet implements both, min and max, with some basic type checking and returning NaN if one element is not a number.

var Math1 = {
    min: function(values) {
        if(values.length == 0) {
            return NaN;
        } else if(values.length == 1) {
            var val = values.pop();
            if ( typeof val == "number" ) {
                return val;
            } else {
                return NaN;
            }
        } else {
            var val = values.pop();
            return Math.min(val, this.min(values))
        }
    },
    max: function(values) {
        if(values.length == 0) {
            return NaN;
        } else if(values.length == 1) {
            var val = values.pop();
            if ( typeof val == "number" ) {
                return val;
            } else {
                return NaN;
            }
        } else {
            var val = values.pop();
            return Math.min(val, this.max(values))
        }
    }
}

Math1.min([100,13,3,6]); // 3
Math1.max([100,13,3,6]); // 100

Example #2

The code from the first example works just fine but both functions are pretty much identical except the final min/max operation of the math library. Essentially this is simply code duplication which should always be avoided.

In this example our self-implemented min/max functions use the new function calculate and pass it the Math’s min/max function as an argument.

var Math2 = {
    min: function(values) {
        return this.calculate(values, Math.min);
    },
    max: function(values) {
        return this.calculate(values, Math.max);
    },
    calculate: function(values, operation) {
        if(values.length == 0) {
            return NaN;
        } else if(values.length == 1) {
            var val = values.pop();
            if ( typeof val == "number" ) {
                return val;
            } else {
                return NaN;
            }
        } else {
            var val = values.pop();
            return operation(val, this.calculate(values, operation))
        }
    }
}

Math2.min([100,13,3,6]); // 3
Math2.max([100,13,3,6]); // 100

Example #3

Using apply and built-in functions performs much better than the above examples. And the code is far more readable and shorter, it’s just two lines.

Math.min.apply(Math, [100,13,3,6]); // 3
Math.max.apply(Math, [100,13,3,6]); // 100

9 Comments

  1. I think you technically don’t need to pass in Math:

    Math.max.apply(null, numbers);

  2. Hi my name is Sandra and I just wanted to drop you a quick note here instead of calling you. I came to your Calculating the min/max value from an array in JavaScript | Slopjong page and noticed you could have a lot more visitors. I have found that the key to running a popular website is making sure the visitors you are getting are interested in your subject matter. There is a company that you can get targeted traffic from and they let you try their service for free for 7 days. I managed to get over 300 targeted visitors to day to my site. Visit them here: http://innovad.ws/2dttq

  3. Peter

    Hi!
    I have a question. Is it possible that min/max functions only work on arrays of a certain maximum size? I’m trying to use your Example #3 on array of 250 thousand numbers, and it does not work.

  4. nnd

    I went over this site and I believe you have a lot of fantastic
    info, saved to favorites (:.

  5. Rattling wonderful information can be found on blog.

  6. Y

    I use very simple
    Math.max.apply(Math,arr)
    Math.min.apply(Math,arr)

  7. What’s up,I read your blog named “Calculating the min/max value from an array in JavaScript | Slopjong” like every week.Your humoristic style is witty, keep it up! And you can look our website about proxy list.

  8. Wow, that’s what I was seeking for, what a information! existing here at this
    website, thanks admin of this web page.

  9. If you happen to be one of those who is really a deposit inside book and then makes bets until it is gone, you will need to make positive changes to ways one
    which just start winning. In this regard, on the list of crucial points that a trader should
    determine include when you should enter and exit.
    The ticket writers are some of the friendliest around, and
    the sort of place where a number of them would really call you from your first name.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>