Search code examples
javascriptarraysjavascript-objects

Javascript: Removing Semi-Duplicate Objects within an Array with Conditions


I am trying to remove the "Duplicate" objects within an array while retaining the object that has the lowest value associated with it.

~~Original

var array = [
 {
   "time": "2021-11-12T20:37:11.112233Z",
   "value": 3.2
 },
 {
   "time": "2021-11-12T20:37:56.115222Z",
   "value": 3.8
 },
 {
   "time": "2021-11-13T20:37:55.112255Z",
   "value": 4.2
 },
 {
   "time": "2021-11-13T20:37:41.112252Z",
   "value": 2
 },
 {
   "time": "2021-11-14T20:37:22.112233Z",
   "value": 3.2
 }
]

~~Expected Output

var array = [
 {
   "time": "2021-11-12T20:37:11.112233Z",
   "value": 3.2
 },
 {
   "time": "2021-11-13T20:37:41.112252Z",
   "value": 2
 },
 {
   "time": "2021-11-14T20:37:22.112233Z",
   "value": 3.2
 }
]

What I have so far:

var result = array.reduce((aa, tt) => { 
    if (!aa[tt.time]) {
        aa[tt.time] = tt;
    } else if (Number(aa[tt.time].value) < Number(tt.value)) { 
        aa[tt.time] = tt;
    }
    return aa;
}, {});

console.log(result);

I realize the issue with what I am trying to do is that the "time" attribute is not identical to the other time values I am considering as duplicates.

Though for this use case I do not need the time out to ms. YYYY-MM-DDTHH:MM (to the minute) is fine. I am not sure how to implement a reduction method for this case when the time isnt exactly the same. Maybe if only the first 16 characters were checked in the string?

Let me know if any additional information is needed.


Solution

  • So a few issues:

    • If you want to only check the first 16 characters to detect a duplicate, you should use that substring of tt.time as key for aa instead of the whole string.

    • Since you want the minimum, your comparison operator is wrong.

    • The code produces an object, while you want an array, so you still need to extract the values from the object.

    Here is your code with those adaptations:

    var array = [{"time": "2021-11-12T20:37:11.112233Z","value": 3.2},{"time": "2021-11-12T20:37:56.115222Z","value": 3.8},{"time": "2021-11-13T20:37:55.112255Z","value": 4.2},{"time": "2021-11-13T20:37:41.112252Z","value": 2},{"time": "2021-11-14T20:37:22.112233Z","value": 3.2}];
    
    var result = Object.values(array.reduce((aa, tt) => { 
        var key = tt.time.slice(0, 16);
        if (!aa[key]) {
            aa[key] = tt;
        } else if (Number(aa[key].value) > Number(tt.value)) { 
            aa[key] = tt;
        }
        return aa;
    }, {}));
    
    console.log(result);