1

i want to pick highest value from an array so i use math.max function it is working well when i run this only with one array but as i have two different array to first of all i want to join them together so i use concat function but it is not working.

<html xmlns="http://www.w3.org/1999/xhtml">
<head>


<script type="text/javascript">

var maX=[6,1]

var miN=[10,20]

alert(Math.max.apply(maX.concat(miN))


</script>
</head>

<body>
</body>
</html>
Jitender
  • 7,593
  • 30
  • 104
  • 210

4 Answers4

4

apply receives two arguments: the "this" and the argument list. Try

Math.max.apply(null, maX.concat(miN) )

or

Math.max.apply(Math, maX.concat(miN) )
hugomg
  • 68,213
  • 24
  • 160
  • 246
  • i give them two argument but it is not wokring alert(Math.max.apply(null,maX.concat(miN)) – Jitender Mar 16 '12 at 04:04
  • @amit You need one more closing bracket. – Chirag Mar 16 '12 at 04:07
  • @amit: It works for me. Are you using IE by any chance? Also, use the developer console and console.log to test stuff like this instead of `alert`. Its better in many ways. – hugomg Mar 16 '12 at 04:07
  • yes you are right sir, thank u so much, sir one more help i required from your side. actully i am new to this field so i did not aware about console log and developer console can u tell me something about it and how to use it – Jitender Mar 16 '12 at 04:12
  • Depends on what browser you are using. In crome, IE and Safari just press F12. In Firefox you need to download the Firebug addon. – hugomg Mar 16 '12 at 04:17
1

The first argument to apply is the value of this, not a parameter. Try

Math.max.apply(Math, maX.concat(miN))
david
  • 17,925
  • 4
  • 43
  • 57
Mike Samuel
  • 118,113
  • 30
  • 216
  • 245
0

to concat two arrays: var joinedarray = array1.concat(array2)

then do max on the joinedarray EDIT: to do the Math.max on the array refference this answer: JavaScript: min & max Array values?

Community
  • 1
  • 1
dbrin
  • 15,525
  • 4
  • 56
  • 83
  • If you pass an array to max you just get NaN back – hugomg Mar 16 '12 at 04:09
  • correct to do the Math.max on the array refference this answer: http://stackoverflow.com/questions/1669190/javascript-min-max-array-values – dbrin Mar 16 '12 at 04:12
0

The following code concatenates two arrays:

var alpha = ["a", "b", "c"];  
var numeric = [1, 2, 3];  

// creates array ["a", "b", "c", 1, 2, 3]; alpha and numeric are unchanged  
var alphaNumeric = alpha.concat(numeric);  

The following code concatenates three arrays:

var num1 = [1, 2, 3];  
var num2 = [4, 5, 6];  
var num3 = [7, 8, 9];



// creates array [1, 2, 3, 4, 5, 6, 7, 8, 9]; num1, num2, num3 are unchanged  


 var nums = num1.concat(num2, num3);  

The following code concatenates three values to an array:

var alpha = ['a', 'b', 'c'];  

// creates array ["a", "b", "c", 1, 2, 3], leaving alpha unchanged  
var alphaNumeric = alpha.concat(1, [2, 3]);  
Laxman Rana
  • 2,904
  • 3
  • 25
  • 37