我有一个带有电话的阵列和一个时间戳,已将其四舍五入到最近的四分之一。
数组输入附在我的评论的末尾。
我想做的事情相当复杂,我尝试使用map / filter / reduce函数的组合,但是不确定我应该以什么顺序处理它。
以下是我想要的,其中按时间对每个电话进行计数,并按当天的热门电话进行排序-此外,对于不存在的小时数,它必须显示0。
理想的输出:
[{
"OPPO R11s": [{
"time": 00:00,
"count": 20
}, {
"time": 00:15,
"count": 13
}, {
"time": 00:30,
"count": 0
}, {
"time": 00:45,
"count": 23
}],
"iPhone 7": [{
"time": 00:00,
"count": 20
}]
}]
输入:
[
{
"phone": "OPPO R11s",
"roundedTime": "10:45"
},
{
"phone": "iPhone 7",
"roundedTime": "03:15"
},
{
"phone": "Samsung Galaxy XCover 4",
"roundedTime": "11:45"
},
{
"phone": "iPhone XS Max",
"roundedTime": "12:00"
},
{
"phone": "iPhone XS",
"roundedTime": "01:00"
},
{
"phone": "Samsung Galaxy Note9",
"roundedTime": "02:30"
},
{
"phone": "Samsung Galaxy J4",
"roundedTime": "07:15"
},
{
"phone": "iPhone XS Max",
"roundedTime": "03:00"
},
{
"phone": "Samsung Galaxy J4 Plus",
"roundedTime": "02:45"
},
{
"phone": "iPhone 6s",
"roundedTime": "12:45"
},
{
"phone": "iPhone XS Max AirPods Bundle",
"roundedTime": "01:00"
}]
进一步说明:
答案 0 :(得分:0)
好-我想你想要的是
包含电话名称以及所有使用该电话的时间的列表的对象数组。数组应该排序。
首先通过输入,使用计数器将条目添加到地图中。每次出现手机时,请搜索其时间列表。如果存在时间,则增加它,如果不增加时间。然后将电话列表映射到带有将电话数据包装到电话名称的对象的数组。移动计数并排序
const phoneMap = {};
const log = [
{
"phone": "OPPO R11s",
"roundedTime": "10:45"
},
{
"phone": "iPhone 7",
"roundedTime": "03:15"
},
{
"phone": "Samsung Galaxy XCover 4",
"roundedTime": "11:45"
},
{
"phone": "iPhone XS Max",
"roundedTime": "12:00"
},
{
"phone": "iPhone XS",
"roundedTime": "01:00"
},
{
"phone": "Samsung Galaxy Note9",
"roundedTime": "02:30"
},
{
"phone": "Samsung Galaxy J4",
"roundedTime": "07:15"
},
{
"phone": "iPhone XS Max",
"roundedTime": "03:00"
},
{
"phone": "Samsung Galaxy J4 Plus",
"roundedTime": "02:45"
},
{
"phone": "iPhone 6s",
"roundedTime": "12:45"
},
{
"phone": "iPhone XS Max AirPods Bundle",
"roundedTime": "01:00"
}];
log.forEach(function(logItem) {
if (!phoneMap[logItem["phone"]]) {
phoneMap[logItem["phone"]] = {count:1, times:[]};
} else {
phoneMap[logItem["phone"]]["count"]++
}
var timeNode = phoneMap[logItem["phone"]]["times"].find(function(timeNode) {
return timeNode["time"] === logItem["roundedTime"];
})
if (timeNode) {
timeNode["count"]++;
} else {
phoneMap[logItem["phone"]]["times"].push({
"time": logItem["roundedTime"],
"count":1
});
}
})
var result = Object.keys(phoneMap).map(function(key){
let obj = {};
obj[key] = phoneMap[key];
obj["count"] = phoneMap[key].count;
delete phoneMap[key]["count"];
return obj;
}).sort(function(a,b){
return b.count - a.count;
});
console.log(result);