0

How do I select the variable associated with the highest number? If I have p1 =1 , p2=4 and p3=3, how can I make the program choose the highest one(in this case p2?)

3
  • You need to scope them... Commented Dec 6, 2019 at 2:58
  • Please share the code you have tried so far Commented Dec 6, 2019 at 2:59
  • You asked how the program can choose a given variable (which for me makes little sense), but I reckon you simply want the value instead: consr foo = Math.max(p1, p2, p3). Commented Dec 6, 2019 at 3:00

1 Answer 1

1

You should apply a scope to the parameters, so that you reduce the number of variables you need to scan for.

let myScope = {};

myScope.p1 = 1;
myScope.p2 = 4;
myScope.p3 = 3;

console.log(getHighest(myScope)); // 4

function getHighest(scope) {
  return Math.max.apply(Math, Object.values(scope));
}

Note: A better alternative would be to have a variable called p to store the values e.g.

var p = [ 1, 4, 3 ];
var max = Math.max.apply(Max, p);

NOT ADVISED: You could also access them from the window, but this is tricker...

var p1 = 1;
var p2 = 4;
var p3 = 3;

console.log(getHighest(window, /^p\d$/)); // 4

function getHighest(scope, pattern) {
  return Math.max.apply(
    Math,
    Object.keys(scope)
      .filter(k => k.match(pattern))
      .map(k => scope[k])
  );
}

Sign up to request clarification or add additional context in comments.

6 Comments

This is not necessary.
In case anyone reading this asks "why not just Math.max(p1, p2, p3)", this approach does not require you to manually key in your keys everytime you add values to the scope. This can also be done using Array instead of object literal.
@YongQuan indeed, but look at the word need: "You need to apply a scope to the parameters...". And also a comment in the question, by the same answerer: "You need to scope them". It's not necessary.
@GerardoFurtado I agree. You don't need to do this if your context doesn't require dynamically adding values.
@MarkMeyer I went ahead and updated/annotated the response. Thanks.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.