1. 程式人生 > >將一個js陣列按日期分組的實現方法

將一個js陣列按日期分組的實現方法

舉例說明:

產品需求:
這裡寫圖片描述

假如後臺返回格式:
var data = [
    {"time": 1517482336545, "location": "浦東"},
    {"time": 1517482336543, "location": "靜安"},
    {"time": 1516344919173, "location": "內環"},
    {"time": 1515574927334, "location": "五環"},
    {"time": 1517482336544, "location": "蘇州"}
];
這就需要前臺再處理成我們需要的資料了。
步驟:將毫秒轉換成日期格式----處理陣列---返回需要的資料格式[{time
:"",location:[]}] 方法: //轉換時間 function transDate(n) { var date = new Date(n); var Y = date.getFullYear() + '-'; var M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-'; var D = date.getDate() < 10 ? '0' + date.getDate() : date.getDate(); return (Y + M + D) } //
處理原陣列 for(var i=0;i<arr.length;i++){ var timeitem = transDate(arr[i].time); console.log(arr[i].time); arr[i].time = timeitem; } //返回所需資料格式 const mapLoction = function(arr) { let newArr = []; arr.forEach((address, i) => { let index = -1; let alreadyExists = newArr.some((newAddress, j) => { if
(address.time === newAddress.time) { index = j; return true; } }); if (!alreadyExists) { newArr.push({ time: address.time, location: [address.location] }); } else { newArr[index].location.push(address.location); } })
; return newArr; }; console.log(mapLoction(data)); 之後就是渲染資料了
列印結果:

這裡寫圖片描述