Home > Software engineering >  Return Object Key based on Value
Return Object Key based on Value

Time:04-01

I need to return the key of an object based on the greatest value of its object[value]. For example:

const myObj = {
    a: 100,
    b: 200,
    c: 300
}

I need a function that would return c (given that c has the highest numerical value)

CodePudding user response:

Object.keys(myObj).reduce((acm, current) => {
    if (acm) {
        return myObj[acm] > myObj[current] ? acm : current;
    }
    return current;
}, null);

CodePudding user response:

const myObj = {
    a: 100,
    b: 200,
    c: 300
};
res = Object.keys(myObj).sort((b,a) => myObj[a]-myObj[b]);
console.log(res); // [ "c", "b", "a" ]
// for highest use res[0]

CodePudding user response:

function fn(obj) {
    return Object.entries(obj).reduce((v, maximum) => maximum[1] < v[1] ? v : maximum)[0]
}

CodePudding user response:

   function getMaxValueKey(obj){
  return Object.keys(obj).reduce((a, b) => obj[a] > obj[b] ? a : b);
}

Reference

  • Related