JavaScript如何根据customer_id从对象数组中获取最新唯一数据
实现方案
你可以借助Map来实现按customer_id去重,同时保留每个customer_id对应的最大id(即最新)条目,代码如下:
// 原始数组 const originalArr = [ {id: 408, customer_id: 2, bill_no: 381, bill_period: 'weekly', from_date: '2021-10-10'}, {id: 409, customer_id: 3, bill_no: 382, bill_period: 'weekly', from_date: '2021-10-10'}, {id: 410, customer_id: 4, bill_no: 383, bill_period: 'weekly', from_date: '2021-10-10'}, {id: 411, customer_id: 6, bill_no: 384, bill_period: 'weekly', from_date: '2021-10-10'}, {id: 412, customer_id: 7, bill_no: 385, bill_period: 'weekly', from_date: '2021-10-10'}, {id: 413, customer_id: 8, bill_no: 386, bill_period: 'weekly', from_date: '2021-10-10'}, {id: 414, customer_id: 9, bill_no: 387, bill_period: 'weekly', from_date: '2021-10-10'}, {id: 387, customer_id: 2, bill_no: 360, bill_period: 'weekly', from_date: '2021-10-03'}, {id: 388, customer_id: 3, bill_no: 361, bill_period: 'weekly', from_date: '2021-10-03'}, {id: 389, customer_id: 4, bill_no: 362, bill_period: 'weekly', from_date: '2021-10-03'}, {id: 390, customer_id: 6, bill_no: 363, bill_period: 'weekly', from_date: '2021-10-03'}, {id: 391, customer_id: 7, bill_no: 364, bill_period: 'weekly', from_date: '2021-10-03'}, {id: 392, customer_id: 8, bill_no: 365, bill_period: 'weekly', from_date: '2021-10-03'}, {id: 393, customer_id: 9, bill_no: 366, bill_period: 'weekly', from_date: '2021-10-03'}, {id: 380, customer_id: 2, bill_no: 353, bill_period: 'weekly', from_date: '2021-09-26'}, {id: 381, customer_id: 3, bill_no: 354, bill_period: 'weekly', from_date: '2021-09-26'}, {id: 382, customer_id: 4, bill_no: 355, bill_period: 'weekly', from_date: '2021-09-26'}, {id: 383, customer_id: 6, bill_no: 356, bill_period: 'weekly', from_date: '2021-09-26'}, {id: 384, customer_id: 7, bill_no: 357, bill_period: 'weekly', from_date: '2021-09-26'}, {id: 385, customer_id: 8, bill_no: 358, bill_period: 'weekly', from_date: '2021-09-26'}, {id: 386, customer_id: 9, bill_no: 359, bill_period: 'weekly', from_date: '2021-09-26'} ] // 去重逻辑 const customerMap = new Map() originalArr.forEach(item => { // 仅当Map中无当前customer_id,或当前条目id更大时更新 if (!customerMap.has(item.customer_id) || item.id > customerMap.get(item.customer_id).id) { customerMap.set(item.customer_id, item) } }) // 转换为结果数组 const result = Array.from(customerMap.values()) console.log(result)
逻辑说明
- 用
Map存储已遍历过的customer_id对应的条目,键为customer_id,值为对应的对象 - 遍历原始数组时,每次判断当前条目是否比已存储的同
customer_id条目id更大,是就更新 - 最后把Map的所有值转为数组,就是你需要的去重后结果
如果你的原始数组本身已经按id从大到小排序(你给出的示例数组恰好是这个顺序),可以简化判断逻辑,直接判断Map中是否不存在该customer_id再存入即可,不用对比id大小,遍历完结果是一样的。
内容的提问来源于stack exchange,提问作者Mohammed
相关产品推荐
相关产品推荐

