Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
132 views
in Technique[技术] by (71.8m points)

javascript - 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

question from:https://stackoverflow.com/questions/65920614/remove-duplicate-values-from-json-array-based-on-key-date-in-js

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
const obj = arr.reduce((init, item)=> (init[item.EndDate] && item.StartDate > init[item.EndDate] ? ({...init,[item.EndDate]: init[item.EndDate]}) : ({ ...init,[item.EndDate]: item.StartDate}) ), {})
const result = Object.entries(a).map(([k,v])=> ({StartDate: v, EndDate: k}))

This is my code.

Step 1: I convert it to obj with EndDate as key and StartDate as values of keys. After that, I checked StartDate with StartDate in obj if it exists

Step 2: I convert the object to an array

I hope helpful for you


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...