0

I am trying to do something very simple but I can't get it to work. I have 3 variables:

abc = 123
def = 456
ghi = 789

I created array like this:

numbers = [abc, def, ghi]

Then I did this:

Math.max.apply(null, numbers)

It returned 789, then I tried to do:

numbers.indexOf(789)

but it returns 2 = index of ghi, problem is I wanna find "ghi" name exactly and I am struggling.

2
  • Can you elaborate more what you are looking? Commented Jan 22, 2019 at 4:07
  • I want to return variable name so I can use it later Commented Jan 22, 2019 at 4:09

4 Answers 4

1

You need to store the labels in your array as well. JavaScript is not able to read your variable name during your program's execution:

const abc = 123;
const def = 456;
const ghi = 789;

const numbers = [
  {label: 'abc', value: abc},
  {label: 'def', value: def},
  {label: 'ghi', value: ghi}
];

const max = Math.max.apply(null, numbers.map(v => v.value));
console.log(max);

const maxObject = numbers.find(n => n.value === max);
console.log(maxObject.label);

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

Comments

1

If you use associative array then you dont need objects. here a sample solution using an array

findMax = () => {
  // define the array
  let array = [];
  // filling items to the array
  array['a'] = 123;
  array['b'] = 456;
  array['c'] = 789;

  // variables for max and maxKey
  let max = 0;
  let maxKey = '';
  
  // iterate through the assoc array
  for (var key in array) {
    if(max <= array[key]){
      max = array[key];
      maxKey = key
     }
  }
  console.log('max key ' + maxKey + ' max value ' + max);
}
<input type='button' onclick='findMax()' value='find max' />

Comments

0

You should use Object instead of Array.

const abc = 123;
const def = 456;
const ghi = 789;

const numbers = { abc, def, ghi };
const max = Math.max.apply(null, Object.values(numbers));
const [variableName] = Object.entries(numbers).find(([el, val]) => val === max);

console.log(variableName)

Solution 👇

Edit max variable name

Comments

0

As you have unique labels for values, I would define your data as an object. Then you can build a simple reducer to return the label and the value together:

const numbers = {
  abc: 123,
  def: 456,
  ghi: 789
}

const [label, value] = Object.entries(numbers).reduce((a, b) => a[1] > b[1] ? a : b)
console.log(label, value)

The benefits of storing your variables in this way, is that you can quickly access your values by label simply by using numbers['abc'] for example.

Comments

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.