我有两个数字a和b的数组,我想从这个数组中找到最接近的数字对。但我被困在reducer中,给定了匹配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)
答案 0 :(得分: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)
答案 1 :(得分:0)
您可以生成cartesian product并按差异排序。
var a = [1, 2, 3, 8],
b = [4, 5, 6],
result = a
.reduce((r, c) => r.concat(b.map(d => ({ dif: Math.abs(c - d), val: c, to: d }))), [])
.sort((a, b) => a.dif - b.dif);
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
答案 2 :(得分:0)
另一种选择:
const a = [1, 2, 3, 8],
b = [4, 5, 6];
const result = b.map(v => {
return a.reduce((re, value) => {
let updateRule = re.val === undefined || (re.val !== undefined && Math.abs(value - re.to)) < re.dif;
return updateRule ? { val: value, dif: Math.abs(value - re.to), to: v } : re;
}, { to: v });
});
console.log(result);
&#13;