【发布时间】:2020-09-11 23:19:36
【问题描述】:
我需要使用一个将对象数组作为参数并解决所有三种情况的函数来解决以下问题。 给定一个对象数组,如何根据几个条件将它们分组为子数组?我正在寻找支付系统中的错误,并希望收到一组重复交易(按交易时间升序排序)。
在以下情况下,交易被视为重复:制造商、金额、类别完全相同且交易之间的时间少于 45 秒。
我正在寻找一个 ES6 解决方案,我确信它会包含 .reduce 方法。
我尝试处理它,通过遵循 reduce 给我一个基于制造商密钥的对象,这不是我想要实现的结果,因为我需要子数组而不是对象,并且需要更多的条件而不仅仅是制造商。
let groupedArr = data.reduce((accumulator, currentValue) => {
accumulator[currentValue.manufacturer] = [...accumulator[currentValue.manufacturer] || [], currentValue];
return accumulator;
}, {});
案例一:
输入:
const data = [{
id: 3,
manufacturer: 'audi',
amount: 40,
category: 'leasing',
transaction: '2020-03-02T10:34:30.000Z'
},
{
id: 4,
manufacturer: 'audi',
amount: 40,
category: 'leasing',
transaction: '2020-03-02T10:34:38.000Z'
},
{
id: 1,
manufacturer: 'mercedes',
amount: 20,
category: 'leasing',
transaction: '2020-03-05T12:00:00.000Z'
},
{
id: 7,
manufacturer: 'audi',
amount: 40,
category: 'leasing',
transaction: '2020-03-20T11:00:00.000Z'
},
{
id: 6,
manufacturer: 'mercedes',
amount: 20,
category: 'leasing',
transaction: '2020-03-05T12:00:44.000Z'
},
{
id: 2,
manufacturer: 'volkswagen',
amount: 2,
category: 'credit',
transaction: '2020-03-05T12:00:45.000Z'
},
{
id: 5,
manufacturer: 'audi',
amount: 40,
category: 'leasing',
transaction: '2020-03-02T10:35:17.000Z'
},
]
预期输出:
[[{
id: 3,
manufacturer: 'audi',
amount: 40,
category: 'leasing',
transaction: '2020-03-02T10:34:30.000Z'
},
{
id: 4,
manufacturer: 'audi',
amount: 40,
category: 'leasing',
transaction: '2020-03-02T10:34:38.000Z'
},
{
id: 5,
manufacturer: 'audi',
amount: 40,
category: 'leasing',
transaction: '2020-03-02T10:35:17.000Z'
}],
[{
id: 1,
manufacturer: 'mercedes',
amount: 20,
category: 'leasing',
transaction: '2020-03-05T12:00:00.000Z'
},
{
id: 6,
manufacturer: 'mercedes',
amount: 20,
category: 'leasing',
transaction: '2020-03-05T12:00:44.000Z'
}]
]
案例2:
输入:
const data = [{
id: 2,
manufacturer: 'audi',
amount: 40,
category: 'leasing',
transaction: '2020-03-02T10:34:30.000Z'
},
{
id: 7,
manufacturer: 'audi',
amount: 40,
category: 'leasing',
transaction: '2020-03-20T11:00:00.000Z'
}]
预期输出:
[]
解释:事务之间超过 45 秒应该输出一个空数组。
案例3:
输入:
const data = [{
id: 2,
manufacturer: 'audi',
amount: 40,
category: 'leasing',
transaction: '2020-03-02T10:34:30.000Z'
},
{
id: 1,
manufacturer: 'audi',
amount: 40,
category: 'credit',
transaction: '2020-03-02T10:34:40.000Z'
}]
预期输出:
[]
解释:少于 45 秒,但类别不同,因此不被视为重复。
【问题讨论】:
-
“需要更多条件而不仅仅是制造商” - 然后不要只使用制造商键作为属性名称。 “我需要子数组而不是对象” - 将条目分组后进行转换。
-
为什么 id=2 (volkswagen, credit) 不包含在案例 1 的输出中?请参阅我对案例 1 的回答,我不明白您为什么要排除它。此外,当存在重复时(在 40 秒内,保留哪一个 - 时间上“较早”的那个?)。请尝试解释这一点,并尽可能让您的问题更清楚。
-
重复的ID总是一样吗? (因为这里有两个 id=5 的 Audi 条目,它们在 40 秒内) - 两次使用相同的 id 是不好的做法,但如果这意味着重复也很容易解决。
-
完美,我的回答应该能满足你现在的期望。
标签: javascript arrays reduce