1

How can I get the minimum value from an array in JavaScript? I did try the Math.min method and it seems that it doesn't work as expected.

As an example, I have four divs with numeric values:

HTML:

<div id="r">3121</div>
<div id="g">2334</div>
<div id="b">3445</div>
<div id="a">4121</div>

JavaScript:

var r = $('#r').text(),
    g = $('#g').text(),
    b = $('#b').text(),
    p = $('#a').text();

var mainBox = [r,g,b,a];
var minN = Math.min(mainBox);
alert(minN);

Can you please tell me what am I doing wrong?

John Skoumbourdis
  • 3,041
  • 28
  • 34
Mongo
  • 151
  • 7

6 Answers6

4

Update answer: This solution is now working

  1. You have to do it with parseInt(..., 10).
  2. The Math.min doesn't accept arrays.

So in your case you will have something like this:

function getMinFromArray (array_of_values) {
    return array_of_values.sort()[0];   
};

var r = parseInt($('#r').text(), 10),
    g = parseInt($('#g').text(), 10),
    b = parseInt($('#b').text(), 10),
    p = parseInt($('#a').text(), 10);

var mainBox = [r,g,b,a];
var result = getMinFromArray(mainBox);

alert(result);

This is a working example: http://jsfiddle.net/CJfWu/2/

John Skoumbourdis
  • 3,041
  • 28
  • 34
2

I don't think you can pass an array to Math.min() like that.

Try it like this:

var minValue = Math.min.apply(Math, mainBox);

Or just use it like this:

var minValue = Math.min(r,g,b,p);
nl-x
  • 11,762
  • 7
  • 33
  • 61
1

Working fiddle fiddle

Use following code

//parseInt to convert String => Int.
var    r = parseInt($('#r').text(),10);
var    g = parseInt($('#g').text(),10);
var    b = parseInt($('#b').text(),10);
var    p = parseInt($('#a').text(),10);

//Here sort the values
var minN = Math.min(r,g,b,p);
alert(minN);
Pratik Joshi
  • 11,485
  • 7
  • 41
  • 73
0

Try this:

var r = parseInt($('#r').text(), 10),
    g = parseInt($('#g').text(), 10),
    b = parseInt($('#b').text(), 10),
    p = parseInt($('#a').text(), 10);

var minN=Math.min(r,g,b,p);
alert(minN);

As .min() does not accept array argument rather just comma separated integers, so you would place your integers one by one and it will return the minimum value.

Hammad
  • 2,097
  • 3
  • 26
  • 45
0

You may try this:

var vals = [];
$('#r, #g, #b, #a').each(function(i){
    vals[i] = $(this).text();
});
var min = Math.min.apply(Math, vals);
The Alpha
  • 143,660
  • 29
  • 287
  • 307
0

I prefer to use a general solution for any number of divs that contain numbers. First, add a class for those divs with numbers as their text. For example, class="items". Then use the following function to get the minimum values

var getMinValueForDivs = function (divsClass) {
    var itemDivs = $('.' + divsClass);
    var values = [];
    itemDivs.each(function (index, item) {
        values.push(item.innerHTML);
    });

    return Math.min.apply(this, values);
}

Ex:

$(document).ready(function () { 
    getMinValueForDivs('items'); 
});
Oday Fraiwan
  • 1,147
  • 1
  • 9
  • 21