查找具有最大值的对象 属性,其中 属性 是小数

Finding the object property with the highest value where the property is a decimal

我目前正在使用:

last = Math.max.apply(Math, response.data.map((o: any) => {
   return o.name; 
}))

在 response.data 数组中找到具有最高 'name' 值的对象。尽管 16.12 是最大值,但它 returns 16.9 因为我认为它只是查看 1 并跳过它。我怎样才能让它考虑到完整的小数点?

已编辑: 通过的数据是:

const array = [{
    name: 16.3
  },
  {
    name: 16
  },
  {
    name: 17
  },
  {
    name: 17.3
  },
  {
    name: 19
  }
]


console.log(Math.max(...array.map(({name}) => name % 1 !== 0 && name)))

SemVer 各个组件的上下文中,majorminorpatch 是整数,但是复合值 major.minor.patch 本身不是有效数字。这就是为什么它们存储为字符串,句点只是一个分隔符而不是小数点。

要正确比较版本,您需要将字符串分解成它们的组成部分并分别比较每对数字。以下示例通过按降序排序然后取第一个值来执行此操作。

Note: As it is unclear from the question what exactly the requirements are, abbreviated versions e.g. 1.1, will be treated as 1.1.0 here for the sake of simplicity - where typically it is more idiomatic to say that 1.1 represents the highest version of 1.1.x available for a given set.

const cmpVersionDesc = (a, b) => {
    const as = a.split('.').map(Number)
    const bs = b.split('.').map(Number)

    return (bs[0]||0) - (as[0]||0)
        || (bs[1]||0) - (as[1]||0)
        || (bs[2]||0) - (as[2]||0)
}

const latestVersion = versions => 
    [...versions].sort(cmpVersionDesc)[0]
    
 const versions = [
    '16.9',
    '16.12',
    '16.12.1',
    '16.1'
]

console.log('latest', latestVersion(versions)) // '16.12.1'