2017-06-13 20 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);

相关问题