数値aとbの2つの配列があり、この配列から最も近い数値のペアを見つけたいと思います。しかし、私はレデューサーの中に閉じ込められており、マッチが与えられていto
ます。
期待される出力は
[
{
"dif": 1,
"val": 3,
"to": 4
},
{
"dif": 2,
"val": 3,
"to": 5
},
{
"dif": 2,
"val": 8,
"to": 6
}
]
const a = [1,2,3,8]
, b = [4,5,6]
const result = b.map(to => {
return a
.map(v => {return {val:v}})
.reduce((prev, curr) => {
return Math.abs(curr.val - to) < Math.abs(prev.val - to) ? {dif:Math.abs(prev.val - to), val:curr.val, to} : {dif: Math.abs(prev.val - to), val:prev.val, to}
});
})
console.log(result)
コードに1つの修正があります。{dif:Math.abs(prev - to), val:curr.val, to}
する必要があります{dif:Math.abs(curr.val - to), val:curr.val, to}
const a = [1,2,3,8]
, b = [4,5,6]
const result = b.map(to => {
return a
.map(v => {return {val:v}})
.reduce((prev, curr) => {
return Math.abs(curr.val - to) < Math.abs(prev.val - to) ? {dif:Math.abs(curr.val - to), val:curr.val, to} : {dif: Math.abs(prev.val - to), val:prev.val, to}
});
})
console.log(result)
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加