search

Home  >  Q&A  >  body text

Use methods from apply

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...

Here is a short code snippet that contains 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

P粉718730956P粉718730956259 days ago507

reply all(2)I'll reply

  • P粉846294303

    P粉8462943032024-04-04 11:41:14

    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:

    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 extension syntax instead of apply, brackets instead of new Array, and you can use class syntax, since Complex is actually a class. < /p>

    reply
    0
  • P粉306523969
  • Cancelreply