[英]Find biggest number in JS array and return variable name
I am trying to do something very simple but I can't get it to work. 我正在尝试做一些非常简单的事情,但是我无法使其正常工作。 I have 3 variables: 我有3个变量:
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: 它返回789,然后我尝试执行以下操作:
numbers.indexOf(789)
but it returns 2 = index of ghi, problem is I wanna find "ghi" name exactly and I am struggling. 但它返回2 = ghi的索引,问题是我想准确找到“ ghi”的名称,但我很挣扎。
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: JavaScript在程序执行期间无法读取您的变量名:
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);
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' />
You should use Object instead of Array. 您应该使用Object而不是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 👇 解决方案👇
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: 然后,您可以构建一个简单的reducer以将标签和值一起返回:
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. 以这种方式存储变量的好处是,您可以简单地通过使用numbers['abc']
来通过标签快速访问值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.