为了账号安全,请及时绑定邮箱和手机立即绑定

如何根据对象中的属性合并对象数组中的对象

如何根据对象中的属性合并对象数组中的对象

慕哥9229398 2021-08-26 15:18:18
我有一系列的活动,比如this.activities = [{id: 54,event_type: 'CA',user_id: 56,user_name: 'Anand',purpose: disregard,timestamp: 14356787},{id: 54,event_type: 'NA',user_id: 56,user_name: 'Anand',purpose: 'privacy',timestamp: ''},{id: 54,event_type: 'FA',user_id: 56,user_name: 'Anand',purpose: 'Call',timestamp: ''},{id: 54,event_type: 'FA',user_id: 56,user_name: 'Anand',purpose: 'Listen',timestamp: ''},{id: 54,event_type: 'CA',user_id: 56,user_name: 'Anand',purpose: 'Not allowed',timestamp: 14356784},{id: 54,event_type: 'NA',user_id: 56,user_name: 'Anand',purpose: 'data',timestamp: 14356786},{id: 54,event_type: 'CA',user_id: 56,user_name: 'Anand',purpose: 'voicemail',timestamp: 14356785},{id: 54,event_type: 'CA',user_id: 56,user_name: 'Anand',purpose: 'phone',timestamp: 14356775},{id: 54,event_type: 'CA',user_id: 56,user_name: 'Anand',purpose: 'email',timestamp: 14356776},{id: 54,event_type: 'CA',user_id: 56,user_name: 'Anand',purpose: 'letter',timestamp: 14356777}]我想根据每个活动的5ms时间戳差异,仅通过 event_type 'CA' 对该数组进行分组/过滤。因此,如果 event_type 为“CA”的活动的时间戳彼此相差在 5ms 之内,那么将这些活动分组并形成一个新活动,除了称为 CA_combined 的俱乐部活动的新 event_type 之外,所有内容都相同。
查看完整描述

2 回答

?
慕尼黑5688855

TA贡献1848条经验 获得超2个赞

解决了这个 O(n) 解决方案


 sortedCAarray.forEach((act, index) => {

        const currActivityTime = moment(act.timestamp).valueOf()

        console.log(currActivityTime)

        //  First element is already added, avoid duplicates

        if (index < 1) return

        // Grab the last key from the timestampMap

        const timestampKeys = Object.keys(timestampMap)

        const key = timestampKeys[timestampKeys.length - 1]

        // Add the activity and purpose to the respective arrays and set for that key if the key is within 5 units of the current activity timestamp

        if (Math.abs(key - currActivityTime) < 5) {

          let activities = timestampMap[key].activities

          let purposes = timestampMap[key].purposes

          activities.push(act)

          purposes.add(act.purpose)

          let timestamp = moment(activities[activities.length - 1].timestamp).valueOf()

          // Edge case to to include all activities in the same bucket if they were within 5 ms of any element within the bucket

          if (timestamp > key) {

            Object.defineProperty(timestampMap, timestamp,

              Object.getOwnPropertyDescriptor(timestampMap, key))

            delete timestampMap[key]

          }

        } else {

          // If not just create a new key with the current activity timestamp as the key

          timestampMap[currActivityTime] = { activities: [act], purposes: new Set([act.purpose]) }

        }

      })

希望对此有任何改进!谢谢


查看完整回答
反对 回复 2021-08-26
  • 2 回答
  • 0 关注
  • 219 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信