How can I find the key of the object with the maximum value in the array?
-
Array = & gt; const arr = [{a: 5}, {b: 3}, {c: 1}, {d: 6}]
Is there anything better than this? In short, brighter ...
Is this a normal decision?
const arr = [{a: 5}, {b: 3}, {c: 1}, {d: 6}]
const sortArr = arr.sort ((a, b) = & gt; Object.values (b) - Object.values (a))
const maxKey = Object.keys (sortArr [0]). join ('')
console.log (maxKey)JavaScript Anonymous, Jul 19, 2019 -
Well, you can. I don't know how brilliant it is and definitely not shorter, but in one pass and without unnecessary sorting of the array.
const arr = [{a:5},{d:6},{g:0},{b:3},{c:1}];
let max = null;
let result;
for (const currentObj of arr) {
const currentValue = currentObj[Object.keys(currentObj)[0]];
const currentKey = Object.keys(currentObj)[0];
if (max < currentObj[currentKey] || max === null) {
max = currentValue;
result = currentKey;
}
}
console.log(result);Samuel Leach -
It can be more efficient, without sorting, in one pass reduce.
You can also write shorteronly it will be difficult to readconst maxKey = arr.reduce((a,c,v)=>(v=Object.values(c)[0],v<a.v?a:{k:Object.keys(c)[0],v:v}),{k:0,v:-Infinity}).k;
If we assume that the values are greater than zero, and return not only the key, but the entire maximum object, then even shorter:
const maxElem = arr.reduce((a,c,v)=>(v=Object.values(c),v<a.v?a:{k:c,v:v}),{k:0,v:0}).k;
Elijah Huerta
xs how much more adequate it is) well, you can store the key and value separately.
let max = arr[0]
arr.slice(1).forEach(function(elem) {if(Object.values(max)[0]<Object.values(elem)[0]) {max = elem}});Anonymous
Some of my game:
const arr = [{a:5},{b:3},{c:1},{d:6}];
let vals = arr.map(v=>Object.values(v)[0]);
let key = Object.keys(arr[vals.indexOf(Math.max(...vals))])[0];
console.log(key)
IMHO: the option BigSmoke is the fastest and also readable for a living person - which is important in our business.Marilyn McClure
Your version is also not bad, add it to him.
console.log(Object.keys(arr.sort(((a, b) =>Object.values(b)-Object.values(a)))[0])[0])
Anonymous
const b = [{a:5},{b:3},{c:1},{d:6}];
const maxValue = Math.max(...b.map(d => Object.values(d)[0]));
const result = Object.keys(b[b.findIndex(c => Object.values(c)[0] === maxValue)])[0]
console.log(result);Anonymous
Your AnswerTo place the code, please use CodePen or similar tool. Thanks you!
6 Answers