我有一个带有值的对象
const source = {
'10': 3,
'15': 3,
'20': 2.5,
'25': 2.5,
'30': 2,
'35': 2,
'40': 2,
'45': 2,
'50': 2,
'55': 1.5,
'60': 1.5,
'70': 1.5,
'80': 1.5,
'90': 1.5,
'100': 1,
'125': 1,
'150': 1,
'200': 0
}
我想用一个词来形容:
const parm = 36.5
我想检索具有键最接近parm值的对。
我试过用地图:
result = Object.keys(source).map((x) => {if (weight - x > 0) { return ({[x]: source[x], diff: (weight - x)}) }} )
这是好的,除了它返回undefined
的非匹配。
我发现了一个关于map()
返回未定义的问题,并且回答认为filter()更合适。
result = Object.keys(source).filter((x) => {if (weight - x > 0) { return ({[x]: source[x], diff: (weight - x)}) }} )
.filter()
更合适,只是它只返回键,我无法跟踪哪个键最适合我想要的一对。
我在这里有点困惑。我可能把这个问题看错了,所以我们也欢迎对这个方法提出建议。
我认为Math.min()
会分离出最好的答案,但我不知道如何使用它,因为我无法比较过滤后的值来获取最小值。
UPDATE修改了我正在复制的问题中的解决方案--我想出了以下内容:
let index
Object.keys(source).forEach((item) => {
let dist = weight - item
if ((dist > 0 && dist < index) || index === undefined) {
index = item
}
})
console.log(source[index])
这就是我的答案。
不过,来自@atomh33ls的答案更优雅。它还降低了日志(N)的复杂度,对吗?
我忘记了reduce()
会解决我访问数组前一个元素的问题。
发布于 2021-01-02 09:10:48
基于this answer,您可以使用reduce
const source = {
'10': 3,
'15': 3,
'20': 2.5,
'25': 2.5,
'30': 2,
'35': 2,
'40': 2,
'45': 2,
'50': 2,
'55': 1.5,
'60': 1.5,
'70': 1.5,
'80': 1.5,
'90': 1.5,
'100': 1,
'125': 1,
'150': 1,
'200': 0
}
let target = 36.5
let key= Object.keys(source).reduce((prev, curr) => Math.abs(curr - target) < Math.abs(prev - target) ? curr : prev);
result = {key:key,value:source[key]}
console.log(result)
https://stackoverflow.com/questions/65537337
复制相似问题