【发布时间】:2019-04-28 02:51:09
【问题描述】:
我有一个交易对象数组,我需要在其中根据属性查找重复项(如果对象的所有值都相同,除了 ID 和 TIME,则对象是重复的,时间差应在 1 分钟内)。 我需要将相同的重复事务组合为一个数组对象。
以下是交易的输入。
我尝试使用 Reduce 函数,但无法获得预期的输出。
var newArray = transactions.reduce(function(acc, curr) {
//finding Index in the array where the NamaCategory matched
var findIfduplicateExist = acc.findIndex(function(item) {
let accepoch = new Date(item.time).valueOf();
let currepoch= new Date(curr.time).valueof();
if(item.sourceAccount === curr.sourceAccount &&
item.targetAccount===curr.targetAccount &&
item.amount===curr.amount&&
accepoch<currepoch+(1*60*1000))
let obj={
'id':curr.id,
'sourceAccount':curr.sourceAccount,
'targetAccount':curr.targetAccount,
'time':curr.time,
'category':curr.category,
'amount':curr.amount
}
})
// if in the new array no such object exist, create a new object
if (findIfNameExist === -1) {
acc.push(obj)
} else {
// if attributes matches , then push the value
acc[findIfNameExist].value.push(curr)
}
return acc;
}, []);
输入交易:
[
{
id: 3,
sourceAccount: 'A',
targetAccount: 'B',
amount: 100,
category: 'eating_out',
time: '2018-03-02T10:34:30.000Z'
},
{
id: 1,
sourceAccount: 'A',
targetAccount: 'B',
amount: 100,
category: 'eating_out',
time: '2018-03-02T10:33:00.000Z'
},
{
id: 6,
sourceAccount: 'A',
targetAccount: 'C',
amount: 250,
category: 'other',
time: '2018-03-02T10:33:05.000Z'
},
{
id: 4,
sourceAccount: 'A',
targetAccount: 'B',
amount: 100,
category: 'eating_out',
time: '2018-03-02T10:36:00.000Z'
},
{
id: 2,
sourceAccount: 'A',
targetAccount: 'B',
amount: 100,
category: 'eating_out',
time: '2018-03-02T10:33:50.000Z'
},
{
id: 5,
sourceAccount: 'A',
targetAccount: 'C',
amount: 250,
category: 'other',
time: '2018-03-02T10:33:00.000Z'
}
];
预期输出如下:
[
[
{
id: 1,
sourceAccount: "A",
targetAccount: "B",
amount: 100,
category: "eating_out",
time: "2018-03-02T10:33:00.000Z"
},
{
id: 2,
sourceAccount: "A",
targetAccount: "B",
amount: 100,
category: "eating_out",
time: "2018-03-02T10:33:50.000Z"
},
{
id: 3,
sourceAccount: "A",
targetAccount: "B",
amount: 100,
category: "eating_out",
time: "2018-03-02T10:34:30.000Z"
}
],
[
{
id: 5,
sourceAccount: "A",
targetAccount: "C",
amount: 250,
category: "other",
time: "2018-03-02T10:33:00.000Z"
},
{
id: 6,
sourceAccount: "A",
targetAccount: "C",
amount: 250,
category: "other",
time: "2018-03-02T10:33:05.000Z"
}
]
]
【问题讨论】:
-
向我们展示你的尝试,即使它没有让你一路走到那里。
-
你需要支持哪个JS-Version?
-
@HerrErker 这是节点 8.1.3
-
@misorude 用我尝试过的代码更新了我的问题。
标签: javascript arrays duplicates javascript-objects