Fast way to get the min/max values among properties of object

后端 未结 11 1923
伪装坚强ぢ
伪装坚强ぢ 2020-12-01 00:44

I have an object in javascript like this:

{ \"a\":4, \"b\":0.5 , \"c\":0.35, \"d\":5 }

Is there a fast way to get the minimum and maximum v

11条回答
  •  暖寄归人
    2020-12-01 01:08

    // 1. iterate through object values and get them
    // 2. sort that array of values ascending or descending and take first, 
    //    which is min or max accordingly
    let obj = { 'a': 4, 'b': 0.5, 'c': 0.35, 'd': 5 }
    let min = Object.values(obj).sort((prev, next) => prev - next)[0] // 0.35
    let max = Object.values(obj).sort((prev, next) => next - prev)[0] // 5
    

提交回复
热议问题