【发布时间】:2020-03-28 22:11:35
【问题描述】:
我试图通过基于逻辑合并它们之间的键来减少对象数组。
说明
我想通过键来减少以下数组(见下文):
-
lines:合并它们之间共有的数字范围(例如:[1,2] + [3,2] = [1,2,3]) -
dates:合并与lines键关联的数组日期
应删除所有重复的数组和/或键。
示例:
输入示例A:
const errors = [
{
"lines": [1, 2],
"dates": [["2020-12-12","2020-12-19"], ["2020-12-13","2020-12-25"]]
},
{
"lines": [1, 3],
"dates": [["2020-12-12","2020-12-19"], ["2020-12-15","2020-12-17"]]
},
{
"lines": [2, 3],
"dates": [["2020-12-13","2020-12-25"], ["2020-12-15","2020-12-17"]]
},
{
"lines": [3, 2],
"dates": [["2020-12-15","2020-12-17"], ["2020-12-13","2020-12-25"]]
}
]
输出示例A:
const expected = [{
lines: [1, 2, 3],
dates: [
["2020-12-12", "2020-12-19"],
["2020-12-13", "2020-12-25"],
["2020-12-05", "2020-12-20"],
["2020-12-15", "2020-12-17"]
]
}];
输入示例B:
const errors = [
{
lines: [1, 2],
dates: [["2020-12-12", "2020-12-19"], ["2020-12-04", "2020-12-25"]]
},
{
lines: [1, 5],
dates: [["2020-12-12", "2020-12-19"], ["2020-12-05", "2020-12-20"]]
},
{
lines: [2, 5],
dates: [["2020-12-04", "2020-12-25"], ["2020-12-05", "2020-12-20"]]
},
{
lines: [3, 4],
dates: [["2020-10-19", "2020-10-25"], ["2020-10-24", "2020-10-27"]]
},
{
lines: [4, 3],
dates: [["2020-10-24", "2020-10-27"], ["2020-10-19", "2020-10-25"]]
},
{
lines: [5, 2],
dates: [["2020-12-05", "2020-12-20"], ["2020-12-04", "2020-12-25"]]
}
];
输出示例B:
const expected = [
{
lines: [1, 2, 5],
dates: [
["2020-12-12", "2020-12-19"],
["2020-12-04", "2020-12-25"],
["2020-12-05", "2020-12-20"]
]
},
{
lines: [3, 4],
dates: [
["2020-10-19", "2020-10-25"],
["2020-10-24", "2020-10-27"]
]
}
];
我创建了一个沙箱来实现这一点: https://codesandbox.io/s/lodash-sandbox-zsr9r
有三个例子,第三个不起作用。
我目前的实现:
const sanatizeErrors = errors.reduce((acc, currentError, i) => {
const nextError = errors[i + 1]
const hasOnlySingleError = errors.length === 1
// The following const is not enough "strong" and it doesn't handle all cases
const hasCommonErrorWithNextLine =
nextError && _.includes(nextError.lines, currentError.lines[0])
if (hasOnlySingleError) {
return [{
lines: currentError.lines,
dates: currentError.dates
}]
}
if (hasCommonErrorWithNextLine) {
return [
...acc,
{
lines: _.uniq([
...currentError.lines,
...nextError.lines
]),
dates: _.uniqWith(
[
...currentError.dates,
...nextError.dates
], _.isEqual)
}
]
}
return acc
}, [])
这个最终数组用于处理动态日期范围重叠。
任何亮点都值得赞赏 =)
【问题讨论】:
-
您在哪一步遇到问题?
-
@SlavaKnyazev 你可以在这里看到codesandbox.io/s/lodash-sandbox-zsr9r 输出数组包括两个实体而不是预期的一个(例如C)。我想我组合“常见”数字的逻辑不够“灵活”。
-
另外请在此处发布您的代码
-
完成。感谢您的帮助
-
我敢打赌这条线路有问题:
_.includes(nextError.lines, currentError.lines[0])。您只检查第一个“行”元素,而您应该检查所有这些元素。
标签: javascript lodash reduce overlap