过滤阵列数组以仅保留每个ID最新日期的元素

时间:2018-05-09 09:52:22

标签: javascript array-filter

如何过滤此数组

    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"]
              ];

我想过滤每个其他子元素(ID)的最新日期元素。要获得此输出:

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

1 个答案:

答案 0 :(得分:0)

一些观察/假设

  1. 日期3/20/2018附近缺少引号。没有引号,这只是一个浮点数
  2. 您的子阵列有3个项目,其中第一个和最后一个项目形成唯一的组合(ID)。
  3. 基于以上所述,您可以尝试以下

    
    
    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));