查找对象中具有最大价值的密钥

时间:2018-12-06 10:04:29

标签: javascript algorithm object data-structures

假设我有一个对象:

DateTime time = DateTime.Now;
bool isWeekend = time.DayOfWeek == DayOfWeek.Saturday || time.DayOfWeek == DayOfWeek.Sunday;

如何查找值最大的属性的名称?例如,在这里:答案应该是“ Angry”,因为其值“ 1.0”是最大的。谢谢您的投入!

5 个答案:

答案 0 :(得分:1)

var maxValue = 0;
var keyVal;
var object = {Angry: "1.0", Fearful: "0.0", Happy: "0.0", Neutral: "0.0", Sad: 
"0.0"};
for (var key in object) {
    let tempValue = parseFloat(object[key]);
    if(maxValue < tempValue) {
          maxValue = tempValue;
          keyVal = key;
    }
}

console.log(keyVal);
// expected output: "Angry"

答案 1 :(得分:0)

您将需要遍历JSON对象的所有属性,并比较每个值以查看哪个值最大。这是实现该目标的一种方法:

var guy1 = {Angry: "1.0", Fearful: "0.0", Happy: "0.0", Neutral: "0.0", Sad: "0.0"};
var guy2 = {Angry: "1.0", Fearful: "2.0", Happy: "0.0", Neutral: "0.0", Sad: "0.0"};
var guy3 = {Angry: "1.0", Fearful: "2.0", Happy: "4.0", Neutral: "0.0", Sad: "0.0"};

biggest(guy1);
biggest(guy2);
biggest(guy3);


function biggest(obj) {
   var max = 0;
   var emotion; 

   Object.keys(obj).forEach(function(e){
     if(max<Number(obj[e])) { max = Number(obj[e]); emotion = e; }
   });

   console.log(emotion, max);
}

答案 2 :(得分:0)

您可以在reduceObject.keys,使用累加器对象跟踪找到的当前最大值。

const obj = {Angry: "1.0", Fearful: "0.0", Happy: "0.0", Neutral: "0.0", Sad: "0.0"}

const largest = Object.keys(obj).reduce((largest, key, i) => {
  obj[key] = parseFloat(obj[key])

  largest = obj[key] > largest.num
    ? { key, num: obj[key] }
    : largest

  return i === Object.keys(obj).length - 1 ? largest.key : largest
}, {
  key: null,
  num: 0
})

console.log(largest)

答案 3 :(得分:0)

您可以尝试

let obj ={Angry: "1.0", Fearful: "0.0", Happy: "0.0", Neutral: "0.0", Sad: "0.0"}

let max= -Infinity;
let keyName;

for(let key in obj){
  let temp  = parseFloat(obj[key]);
  if(temp>max){
    max=temp;
    keyName = key 
  }
}

console.log("Max value is:-" ,max, "\nProperty Name is :-", keyName)

答案 4 :(得分:0)

您可以得到一个结果或多个名称结果,请遵循我的代码:

var obj_1= {Angry: "1.0", Fearful: "0.0", Happy: "0.0", Neutral: "0.0", Sad: "0.0"};
var obj_2 = {Angry: "1.0", Fearful: "1.0", Happy: "0.0", Neutral: "0.0", Sad: "0.0"};
//get only one name max
var result1 = Object.entries(obj_1).sort((a,b)=>(b[1]-a[1]));
console.log(result1[0][0]);

//get list of names max
var list_names = [];
var result2 = Object.entries(obj_2).sort((a,b)=>(b[1]-a[1]));
result2 = result2.filter(current=>{
    if(current[1]==result2[0][1]){
        list_names.push(current[0]);
        return current;
    }
})
// console.log(result2);
console.log(list_names);