Search code examples
javascriptarray-filter

Filter Array of Arrays To Retain Only Elements With Latest Dates Per ID


How to filter this array

    var arr = [[1, "3/20/2018", "A"], [1, "3/20/2018", "B"], 
               [1, "4/20/2018", "A"], [1, "4/20/2018", "B"], 
               [2, "1/30/2018", "A"], [2, "1/30/2018", "B"], 
               [2, "3/30/2018", "A"], [2, "3/30/2018", "B"]
              ];

I want to filter only the elements with the latest dates per other sub-elements (ID) . To have this output:

var result = [[1, "4/20/2018", "A"], [1, "4/20/2018", "B"],
              [2, "3/30/2018", "A"], [2, "3/30/2018", "B"]
             ];

Solution

  • Some observations/assumptions

    1. There were missing quotes around the date 3/20/2018. Without quotes this will only be a floating number
    2. Your sub-array has 3 items, where the first and last items form a unique combination (ID).

    Based on the above, you can try following

    var arr = [[1, "3/20/2018", "A"], [1, "3/20/2018", "B"], [1, "4/20/2018", "A"], [1, "4/20/2018", "B"], [2, "1/30/2018", "A"], [2, "1/30/2018", "B"], [2, "3/30/2018", "A"], [2, "3/30/2018", "B"]];
                 
       var obj = {};
       
       arr.forEach(function(item){
         var id = item[0] + "_" + item[2];
         if(obj[id]) {
           if(new Date(item[1]) > new Date(obj[id][1])) {
              obj[id] = item;  
           }
         } else {
           obj[id] = item;
         }
      });
       
      console.log(Object.values(obj));