To find the maximum value of an array, a simple way is
Math.max.apply(null, myArray)
However, assuming myArray
contains complex numbers, and each complex number has a method magnitude
to calculate the length of the complex number, is there an easy way to find myArray# Maximum value of entries in ##? I could of course make a
loop or a function, but my guess is that javascript has a good one line solution...
function Complex(re, im) { this.real = re; this.imag = im; } Complex.prototype.magnitude = function() { return Math.sqrt(this.real * this.real + this.imag * this.imag); }; var a = new Array(1, 2, 3); ra = Math.max.apply(null, a); // works fine var b = new Array(new Complex(1, 2), new Complex(1, 3), new Complex(1, 4)); rb = Math.max.apply(null, b) console.log(ra) console.log(rb) //NaN without surprise
Originally intended to suggest the same thing, but also give the code a bit of modern syntax, so Unmitigated beat me to it, but it works using map:
Yes, you can use extension syntax instead of apply, brackets instead of new Array, and you can use class syntax, since Complex is actually a class.
You can use
Array#map
to create an array of magnitudes to whichMath.max
is applied.