找到键值接近给定值的对象的有效方法

Ani*_*ole 2 javascript ecmascript-6

我正在使用ES6.假设我有一个如下所示的排序数组.不使用lodash或除jquery之外的任何其他库.

    sortedArray = [
    {a: "a", b: 2, c: "something1"},
    {a: "a1", b: 3, c: "something2"},
    {a: "a2", b: 4, c: "something3"},
    {a: "a3", b: 5, c: "something4"},
    {a: "a4", b: 6, c: "something5"},
    {a: "a5", b: 7, c: "something6"}
]
Run Code Online (Sandbox Code Playgroud)

是否有一种有效的方法来找出其键值b值最接近所提供值的对象.

如果我提供值3.9,它应该返回{a: "a2", b: 4, c: "something3"}.

任何帮助表示赞赏.

had*_*enj 6

随着reduce(所以在大数组上应该很慢......):

sortedArray = [
    {a: "a", b: 2, c: "something1"},
    {a: "a1", b: 3, c: "something2"},
    {a: "a2", b: 4, c: "something3"},
    {a: "a3", b: 5, c: "something4"},
    {a: "a4", b: 6, c: "something5"},
    {a: "a5", b: 7, c: "something6"}
]
const search = 3.9
sortedArray.reduce((p,v)=> Math.abs(p.b-search) < Math.abs(v.b-search) ? p : v)
// {a: "a2", b: 4, c: "something3"}
Run Code Online (Sandbox Code Playgroud)