Remove duplicate values from JSON array based on key (date) in JS

I want to remove duplicate values from array base on key with below conditions.

  1. If End Date is same
  2. 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

26 thoughts on “Remove duplicate values from JSON array based on key (date) in JS”

  1. When someone writes an piece of writing he/she maintains the plan of a user in his/her brain that how a user can understand it.
    Thus that’s why this article is perfect. Thanks!

    Reply

Leave a Comment