首页 > 解决方案 > 从对象数组中查找最大日期并通过在 Javascript 中添加标志来更新

问题描述

下面是一个包含两个属性emp_namedate的对象数组,我想通过添加标记来更新记录,其中date应该是与emp_name对应的其他日期最大的日期。

let arr_of_obj = [{emp_name:'Mark',date:new Date('2018/05/01')},
                  {emp_name:'Mark',date:new Date('2018/05/02')},
                  {emp_name:'John',date:new Date('2018/04/05')},
                  {emp_name:'John',date:new Date('2018/03/22')},
                  {emp_name:'Mark',date:new Date('2018/05/06')}];

假设上面的arr_of_obj应该更新两个条目,即

[{emp_name:'Mark',date:new Date('2018/05/21')},
{emp_name:'Mark',date:new Date('2018/05/22')},
{emp_name:'John',date:new Date('2018/04/15'),max:true},
{emp_name:'John',date:new Date('2018/03/22')},
{emp_name:'Mark',date:new Date('2018/05/26'),max:true}]

标签: javascriptecmascript-6

解决方案


const arr = [{emp_name:'Mark',date:new Date('2018/05/01')},
              {emp_name:'Mark',date:new Date('2018/05/02')},
              {emp_name:'John',date:new Date('2018/04/05')},
              {emp_name:'John',date:new Date('2018/03/22')},
              {emp_name:'Mark',date:new Date('2018/05/06')}]

const max_map = {};   // Holds map of (name => obj_with_max_date) items, 
arr.forEach((item, i)=> {
    // Checking whether emp_name is not stored in map, then store the object 
    // and if `emp_name` is already exists in map, comparing `date` fields
    if (!max_map[item.emp_name] || max_map[item.emp_name].date < arr[i].date) {  
       max_map[item.emp_name] = arr[i];
    }
});

// Traversing the map and assigning flags for each emp_name
Object.keys(max_map).forEach( name => {
   max_map[name].max = true;
});

演示


推荐阅读