javascript - 两个数组中最接近的值的集合
问题描述
我正在寻找一种算法的优化来解决一个可能难以解释的简单问题。当您阅读代码时,我不是在寻找速度或性能,而是在寻找简单性和清晰度。也许有人有比我更聪明的解决方案。我想单行可能是一种矫枉过正。
我有两个按日期排序的单元格集合。每个单元格都可以有一个价格值。我们可以假设同一日期的两个单元格中不可能有价格。我想要一个日期集合,但是日期没有价格:
- 哪个系列的价格与过去最接近
- 如果过去没有价格,请看未来
这是我到目前为止所拥有的(它给出了准确的结果):
const array1 = [
{ date: '2019-11-10' },
{ date: '2019-11-11' },
{ date: '2019-11-12' },
{ date: '2019-11-13' },
{ date: '2019-11-14' },
{ date: '2019-11-15', price: 10 },
{ date: '2019-11-16' },
];
const array2 = [
{ date: '2019-11-10' },
{ date: '2019-11-11' },
{ date: '2019-11-12', price: 10 },
{ date: '2019-11-13' },
{ date: '2019-11-14' },
{ date: '2019-11-15' },
{ date: '2019-11-16' },
];
const merged = Object.values(array1).map((element, index) => {
let filled;
if (element.price) {
filled = 1;
}
if (array2[index].price) {
filled = 2;
}
if (filled) {
return {
date: element.date,
filled
}
} else {
return {
date: element.date
}
}
});
const first = merged.find(element => element.filled);
let currentFill = first && first.filled;
const emptyMap = merged.map((element, index, array) => {
if (!element.filled) {
return {
date: element.date,
empty: currentFill
}
}
currentFill = element.filled;
return element;
})
console.log(emptyMap);
解决方案
const array1 = [
{ date: '2019-11-10' },
{ date: '2019-11-11' },
{ date: '2019-11-12' },
{ date: '2019-11-13' },
{ date: '2019-11-14' },
{ date: '2019-11-15', price: 10 },
{ date: '2019-11-16' },
];
const array2 = [
{ date: '2019-11-10' },
{ date: '2019-11-11' },
{ date: '2019-11-12', price: 10 },
{ date: '2019-11-13' },
{ date: '2019-11-14' },
{ date: '2019-11-15' },
{ date: '2019-11-16' },
];
function collect(collection1, collection2) {
let firstEmptyId = null
let currentId = null
let indexes = [/* [1] optimization */]
let collection = collection1.map(({ date, price }, i) => (
((price && (currentId = 1)) || (collection2[i].price && (currentId = 2)))
? ((firstEmptyId || (firstEmptyId = currentId)), { date, filled: currentId })
: ((firstEmptyId || /*see[1]*/ indexes.push(i)), { date, empty: currentId })
))
// only two iterations => index.length === 2
indexes.forEach((i) => (collection[i].empty = firstEmptyId))
return collection
}
console.log(collect(array1, array2))
推荐阅读
- python - 映射对角线
- java - Java ScheduleExpression:调度程序只在第一个小时工作,为什么?
- python-3.x - 如何在 2 个条形图 python 之间添加空格
- javascript - 如何从受保护的网页重定向到登录页面
- c# - IdentityServer4 添加密码返回 false
- docker - 使用 GCP 上的容器优化操作系统设置 docker 容器名称
- python - 如何使用 textwrap 缩进第二行?
- python - Django - 如何从同一数据库中的另一个表/模型填充模型中的数据?
- ios - Swift如何从源自lib的字符串创建类实例
- python - 3D 动画中每个球体的随机方向