简体   繁体   English

从数组对象中删除重复项 - TypeScript

[英]remove duplicates from array object - TypeScript

Whats the cleanest way of removing duplicates.删除重复项的最干净方法是什么。

0: { taxType: 9, taxCode: "a", taxValidFrom: "01 Jan 2020 00:00:00.000", taxDesc: "a", …}
1: { taxType: 9, taxCode: "C", taxValidFrom: "03 Jan 2020 00:00:00.000", taxDesc: "C", …}
2: { taxType: 9, taxCode: "a", taxValidFrom: "04 Jan 2020 00:00:00.000", taxDesc: "a", …}
3: { taxType: 9, taxCode: "C", taxValidFrom: "05 Jan 2020 00:00:00.000", taxDesc: "C", …}
4: { taxType: 9, taxCode: "B", taxValidFrom: "06 Jan 2020 00:00:00.000", taxDesc: "B", …}

I want to end up with an array where there is one entry based on date and taxcode.我想最终得到一个数组,其中有一个基于日期和税码的条目。

So if taxcode is C, i should only have the one where the date is "05 Jan 2020 00:00:00.000", as this is the closest to todays date (06/01/2020)所以如果税码是 C,我应该只有日期是“05 Jan 2020 00:00:00.000”的,因为这是最接近今天的日期(06/01/2020)

You can loop through each object in the array and push or replace the current object.您可以遍历数组中的每个对象并推送或替换当前对象。

So, the approach can be:因此,该方法可以是:
1. If the taxcode is not present in the final array, push the new object in the final array. 1. 如果税码不存在于最终数组中,则将新对象推送到最终数组中。
2. If the taxcode is already present in the final array, compare the date in both and keep the latest one. 2. 如果税码已存在于最终数组中,则比较两者中的日期并保留最新的。

Suggestion:建议:
You can use a reduce function for the same.您可以使用 reduce 函数。

 function modifyArray(arr) { return arr.reduce((acc, curr) => { const elementIndexInArray = acc.findIndex(a => a.taxCode === curr.taxCode); if(elementIndexInArray === -1) { acc.push(curr); } else if (new Date(acc[elementIndexInArray].taxValidFrom) < new Date(curr.taxValidFrom)) { acc.splice(elementIndexInArray, 1, curr); } return acc; }, []); } var a = [ { taxType: 9, taxCode: "a", taxValidFrom: "01 Jan 2020 00:00:00.000", taxDesc: "a"}, { taxType: 9, taxCode: "C", taxValidFrom: "03 Jan 2020 00:00:00.000", taxDesc: "C"}, { taxType: 9, taxCode: "a", taxValidFrom: "04 Jan 2020 00:00:00.000", taxDesc: "a"}, { taxType: 9, taxCode: "C", taxValidFrom: "05 Jan 2020 00:00:00.000", taxDesc: "C"}, { taxType: 9, taxCode: "B", taxValidFrom: "06 Jan 2020 00:00:00.000", taxDesc: "B"} ]; console.log(modifyArray(a));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM