javascript - 从对象数组中查找最大日期并通过在 Javascript 中添加标志来更新
问题描述
下面是一个包含两个属性emp_name和date的对象数组,我想通过添加标记来更新记录,其中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}]
解决方案
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;
});
推荐阅读
- sql - 将年龄范围 SQL 转换为 Linq 查询
- python - Keras resnet50 get_layer() '没有这样的层' 错误
- javascript - 如何使用 javascript empty 方法清理表数据
- python-3.x - 如何为熊猫数据框列标签设置日期时间格式?
- registry - 高级安装程序未在多用户安装的自动更新上更新/添加注册表项
- python - Python Flask/ReactJS/React 路由器,Heroku 部署 API 调用不适用于 GCP
- reactjs - 隐藏和显示菜单核心 UI
- django - Django 按不同列的顺序不同
- python - 在python中的离散分布之间进行选择
- java - 更改展示视图上的文本大小