亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何根據對象中的屬性合并對象數組中的對象

如何根據對象中的屬性合并對象數組中的對象

慕哥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 關注
  • 244 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號