I want to remove duplicate values from array base on key with below conditions.
- If End Date is same
- If Start Date is small than other then use small start date value.
Below is Input and excepted output.
Input:
[
{
"StartDate": "2020-01-15",
"EndDate": "2020-02-14"
},
{
"StartDate": "2019-12-13",
"EndDate": "2020-01-15"
},
{
"StartDate": "2019-11-13",
"EndDate": "2020-01-15"
},
{
"StartDate": "2019-10-11",
"EndDate": "2019-11-13"
}
]
Output:
[
{
"StartDate": "2020-01-15",
"EndDate": "2020-02-14"
},
{
"StartDate": "2019-11-13",
"EndDate": "2020-01-15"
},
{
"StartDate": "2019-10-11",
"EndDate": "2019-11-13"
}
]
Start date: 2019-12-13 is bigger than 2019-11-13 with same End date 2020-01-15 so it will be remove.
Please suggest me solution.
I have tired with array.some() function but it only returns is value duplicate or not.
Below is my code.
var array = [{"StartDate":"2020-01-15","EndDate":"2020-02-14"},{"StartDate":"2019-12-13","EndDate":"2020-01-15"},{"StartDate":"2019-11-13","EndDate":"2020-01-15"},{"StartDate":"2019-10-11","EndDate":"2019-11-13"}];
var newArray = [];
for (let data of array) {
var result = newArray.some(function (o) {
var d1 = new Date(o["StartDate"]);
var d2 = new Date(data.StartDate);
if (o["EndDate"] === data.EndDate && d1 > d2) {
//console.log(o["StartDate"] +' === '+data.StartDate);
return true;
} else {
return false;
}
});
if (result == false) {
newArray.push({
"StartDate": data.StartDate,
"EndDate": data.EndDate
});
}
}
console.log(newArray);
Thanks
question from:
https://stackoverflow.com/questions/65920614/remove-duplicate-values-from-json-array-based-on-key-date-in-js 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…