To find the maximum of an array, an easy way is
Math.max.apply(null, myArray)
However, assuming that myArray
contains complex numbers, and each complex number has a method magnitude
that computes the length of the complex number, is there a simple way to find the maximum of the magnitude of the entries in myArray
? I could of course do a loop
or a function, but my guess is that javascript has a nice one-line solution…
Here is a short code snippet with all the elements:
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
2
Answers
You can use
Array#map
to create an array of magnitudes to applyMath.max
to.A couple of notes:
[]
to create an array. There is no need to usenew Array()
....
) instead ofFunction#apply
here.Was going to suggest the same, gave the code a little bit modern syntax as well, so Unmitigated beat me to it, but yes use map:
Yes, you can use spread syntax instead of apply, and brackets instead of new Array, and you can use a class syntax since Complex is really a class.