gpt4 book ai didi

javascript - 比较 Javascript 数组对象并返回最接近的对

转载 作者:行者123 更新时间:2023-12-03 01:57:21 24 4
gpt4 key购买 nike

数组 1

[{
"index": 3,
"ratio": 1.9310344827586208
}, {
"index": 0,
"ratio": 2.4122497055359244
}, {
"index": 2,
"ratio": 2.5
}, {
"index": 1,
"ratio": 1
}]

数组2

[{
"index": 0,
"ratio": 0.6670000000000006
}, {
"index": 2,
"ratio": 1
}, {
"index": 3,
"ratio": 1
}, {
"index": 1,
"ratio": 2.409638554216892
}]

我想要这样的结果

从数组 1 比率“2.4122497055359244”和数组 2 比率“2.409638554216892”是最接近的对

[{array1: 0, array2:1}, {array1: 1, array2:2}, ....]

最佳答案

您可以迭代第一个数组并从第二个数组中获取最小的增量。如果有多个项目是最小的,则这两项都包含在结果集中。

结果按最接近的项目排序。

function delta(a, b) {
return Math.abs(a - b);
}

var array1 = [{ index: 3, ratio: 1.9310344827586208 }, { index: 0, ratio: 2.4122497055359244 }, { index: 2, ratio: 2.5 }, { index: 1, ratio: 1 }],
array2 = [{ index: 0, ratio: 0.6670000000000006 }, { index: 2, ratio: 1 }, { index: 3, ratio: 1 }, { index: 1, ratio: 2.409638554216892 }],
result = array1
.reduce((r, a) => r.concat(array2.reduce((s, b) => {
var d1 = s && delta(a.ratio, b.ratio),
d2 = s && delta(a.ratio, s[0].b.ratio);

if (!s || d1 < d2) {
return [{ delta: delta(a.ratio, b.ratio), a, b }];
}
if (d1 === d2) {
s.push({ delta: delta(a.ratio, b.ratio), a, b });
}
return s;
}, undefined)), [])
.sort((a, b) => a.delta - b.delta)
.map(({ a: { index: array1 }, b: { index: array2 } }) => ({ array1, array2 }));

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

只需取第一个最小的增量即可。

function delta(a, b) {
return Math.abs(a - b);
}

var array1 = [{ index: 3, ratio: 1.9310344827586208 }, { index: 0, ratio: 2.4122497055359244 }, { index: 2, ratio: 2.5 }, { index: 1, ratio: 1 }],
array2 = [{ index: 0, ratio: 0.6670000000000006 }, { index: 2, ratio: 1 }, { index: 3, ratio: 1 }, { index: 1, ratio: 2.409638554216892 }],
result = array1
.reduce((r, a) => r.concat(array2.reduce((s, b) => {
var d1 = s && delta(a.ratio, b.ratio),
d2 = s && delta(a.ratio, s[0].b.ratio);

return !s || d1 < d2
? [{ delta: delta(a.ratio, b.ratio), a, b }]
: s;
}, undefined)), [])
.sort((a, b) => a.delta - b.delta)
.map(({ a: { index: array1 }, b: { index: array2 } }) => ({ array1, array2 }));

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

关于javascript - 比较 Javascript 数组对象并返回最接近的对,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50178810/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com