2017-06-13 16 views
1

我試圖以這樣一種方式對數組進行排序,即在一天的開始時間從0:00開始,每隔5分鐘計算一次獨特用戶。 我如何定義時間間隔爲5分鐘的間隔? (使用的數據將是當天的紀元時間),以及如何獲得該間隔的唯一用戶數?以5分鐘的時間間隔對數組進行獨特的數值計數

輸入

[1486428994000, "user a"]  

[1486429834000, "user a"] 

[1486429839000, "user a"] 

[1486429869000, "user b"] 

希望的輸出

[1486428900000, 1 ] 

[1486429800000, 2 ] 
+0

5分鐘(毫秒)信號出現時間是5'* 60 * 1000' ... – deceze

回答

0

要設置一個重複的計時器,可以使用setInterval(function(){},_timeout_)

var T = setInterval(function(){ 
/* code here */ 
}, 1e3*60*5); 

1E3 = 1000(毫秒)
×60(秒)
×5(分鐘)

爲 「現在」 在Javascript中你可以使用:

new Date().valueOf()

取決於哪種類型的時代你使用,你可能有分或100

乘以要獲得唯一值,你可以使用.reduce()https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce

使用客戶端定時器的陷阱:

你的JS時間標記需要機器時間,所以如果客戶機的日期/時間關閉,你的計算將是錯誤的 - 解決這個問題的最好方法是發送服務器時間戳前端並將其轉換爲javascript日期對象並使用該對象,而不是客戶端的機器時間。

如前所述,時代時間戳從服務器軟件不同服務器的軟件,所以你可能需要調整無論是服務器端或客戶端(通常是100倍的差異)

1

// Remove doublons from an array. 
 
const uniq = array => 
 
    array.filter((value, index) => array.indexOf(value) === index); 
 

 
// Your function. 
 
const groupCount = (data, timeWindow) => 
 
    data 
 
    .reduce((groups, line) => { 
 
     const current = groups[groups.length - 1]; 
 
     // If the line is outside of the current time window, push a new group. 
 
     if (!current || line[0] > current[0] + timeWindow) { 
 
     // Find the beginning of the corresponding time window. 
 
     const windowStart = line[0] - line[0] % timeWindow; 
 
     // Push the new group. 
 
     groups.push([windowStart, [line[1]]]); 
 
     } else { 
 
     // Else add a new user to the group. 
 
     current[1].push(line[1]); 
 
     } 
 
     return groups; 
 
    }, []) 
 
    // Once we created the groups, we remove doublons from them and count users. 
 
    .map(group => [group[0], uniq(group[1]).length]); 
 

 
const data = [ 
 
    [1486428994000, "user a"], 
 
    [1486429834000, "user a"], 
 
    [1486429839000, "user a"], 
 
    [1486429869000, "user b"] 
 
]; 
 
console.log(groupCount(data, 5 * 60 * 1000));

0

有了一些時間戳邏輯和一些數組魔法,你可以把它關閉。雖然下面的解決方案返回正確的輸出,但我覺得最終的地圖並非完全必要。如果有人想擴大我的解決方案,請隨時提供。

var raw = [ 
 
    [1486428994000, "user a"], 
 
    [1486429834000, "user a"], 
 
    [1486429839000, "user a"], 
 
    [1486429869000, "user b"] 
 
]; 
 
raw.map(a=> a[0] = parseInt(a[0]/(5 * 60 * 1000)) * (5 * 60 * 1000)); 
 
raw = raw.reduce(function(a,b) { 
 
    if(!a[b[0]]) a[b[0]] = {users: [], count: 0}; 
 
    if(a[b[0]].users.indexOf(b[1]) === -1) { a[b[0]].users.push(b[1]); a[b[0]].count++; } 
 
    return a; 
 
}, {}); 
 
var ret = []; 
 
for(var i in raw) { 
 
    ret.push([i, raw[i].count]); 
 
} 
 
console.log(ret);

相關問題