skip to Main Content

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


  1. You can use Array#map to create an array of magnitudes to apply Math.max to.

    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);
    };
    let b = [new Complex(1,2), new Complex(1,3),  new Complex(1,4)];
    let res = Math.max(...b.map(x => x.magnitude()));
    console.log(res);

    A couple of notes:

    • You can directly use [] to create an array. There is no need to use new Array().
    • You can use spread syntax (...) instead of Function#apply here.
    Login or Signup to reply.
  2. 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:

    class Complex {
    
      constructor(real, imag) {
        this.real = real;
        this.imag = imag;
      }
    
      magnitude() {
        return Math.sqrt(this.real * this.real + this.imag * this.imag);
      };
    }
    
    let a = [1, 2, 3]
    ra = Math.max(...a) // works fine
    
    var b = [new Complex(1, 2), new Complex(1, 3), new Complex(1, 4)];
    rb = Math.max(...b.map(x => x.magnitude()));
    
    console.log(ra)
    console.log(rb) // works now
    

    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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search