1

Possible Duplicate:
JavaScript: min & max Array values?

var test = [-42, 0, 8];
var biggest=-Infinity;
for (i=0; i<test.length;i++)
{if (test[i]>biggest)
    alert('It is!');
  biggest = test[i];
 else
     alert("It isn't!");}
alert("The biggest element is:" + biggest);

I'm trying to write a program to find the biggest number in an array but my code is not working. Any help please?

6
  • 1
    @darvids0n You beat me by 6 seconds. :) Commented Oct 23, 2011 at 23:09
  • test.sort()[test.length-1], just another idea if you're shure it's all numbers. Commented Oct 23, 2011 at 23:14
  • @KooiInc: What about pop() ? Commented Oct 23, 2011 at 23:15
  • @alex: that's all right too, yep. And unshift() then for the lowest value. Commented Oct 23, 2011 at 23:17
  • @KooiInc: sort() converts to strings first, then sorts lexicographically, so you will get not a numeric sort. jsFiddle. Commented Oct 23, 2011 at 23:20

5 Answers 5

8

You have been bitten by the "too few braces" bug:

if (test[i]>biggest)
    alert('It is!');
    biggest = test[i]; // THIS IS NOT INSIDE THE IF!

If you fix this, it works just fine.

Of course, you can do this much easier using Math.Max, as this MDN documentation sample shows:

function getMaxOfArray(numArray) {
  return Math.max.apply(null, numArray);
}
Sign up to request clarification or add additional context in comments.

2 Comments

This is why I always require braces on conditionals... +1
@pst: It's one of those "yeah I know you can do this without braces, but shut up and just use them anyway" issues for me too.
4

This is a bit clever, but quite succinct and works well.

Just call apply() on Math.max() and pass the array as the arguments.

var maxValue = Math.max.apply(null, arr);

jsFiddle.

Comments

1

An alternative solution

function nsort(a,b){
    return a - b;
}
var test = [-42, 0, 8, 3, 15, 12],
    max  = test.sort(nsort).pop(); // 15

Demo: http://jsfiddle.net/TkeHb/

Comments

1

Although you should listen to @alex, this is how you would have done it if there were no Math.max, and you wanted to code C-style:

var test = [-42, 0, 8];

var biggest = -Infinity;

for(var i = 0; i < test.length; ++i)
    if(test[i] > biggest)
        biggest = test[i];

alert("The biggest element is:" + biggest);

6 Comments

Use of prop in array .... generally ick.
@pst Huh? (I'm not much of a JavaScript programmer.)
@muntoo: It will iterate over all enumerable properties in the object, including the prototype chain. Generally unfavorable when dealing with an Array, you want only the numerical indices.
@alex So when would you use foreach()?
@muntoo Array.forEach in ECMAScript ed5, for(i=0;i<len;i++) for EMCAScript ed3 (or whatever function said favorite library provides ;-) This problem is actually well-suited for Array.reduce aka fold, also in ed5.
|
1

ECMAScript 5th Edition introduces a few higher-order functions for arrays -- yay!.

One is Array.reduce (also known as left fold):

Thus, this can be solved as:

var arr = [-42, 0, 8]
var res = arr.reduce(function (prev,cur) {
   return cur > prev ? cur : prev
}, -Infinity)
res // 8

Not nearly as "elegant" in this case as applying the array as the parameters to Math.max, but higher-order functions can make good additions to a "toolbox" ;-) Consider the slight modification to find the longest string in an array:

var arr = ["Hello", "World!!!", "Wut?"]
var res = arr.reduce(function (prev,cur) {
   return cur.length > prev.length ? cur : prev
}, "")
res // "World!!!"

Try that with Math.max or Array.sort and index/pop ;-)

Happy coding.


While the above is for 5th Edition, a trivial reduce function can be written for ECMAScript 3rd Edition (aka JavaScript 1.5) and equivalent functionality is part of a number of libraries:

function reduce (arr, fn, v) {
  for (var i = 0; i < arr.length; i++) {
    v = fn(v, arr[i])
  }
  return v
}
// used as:
reduce(arr, function (prev,cur) { ... }, initValue)

(This could be added to the Array prototype, but I consider mucking with core prototypes fairly ugly.)

1 Comment

+1 for mentioning the modern methods to do this.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.