将一个js数组按日期分组的实现方法
2018-02-07 14:49
671 查看
举例说明:
产品需求:
打印结果:
产品需求:
假如后台返回格式: 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)); 之后就是渲染数据了
打印结果:
相关文章推荐
- 用JS实现一个数组合并的方法(要求去重)
- 编写js扩展方法实现判断一个数组中是否包含某个元素
- JS:调用方法实现向数组中追加一个元素
- 编写js扩展方法实现判断一个数组中是否包含某个元素
- js一个简单的方法实现数组中元素相加
- 一个流行且实用的JS表单验证提示,演示了怎么自定义错误信息的显示方式,同时通过写FormValid.showError类方法来实现错误显示方式自定义: errMsg 是一个错误消息的数组,这样方便自定
- js实现prototype扩展的方法(字符串,日期,数组扩展)
- JS实现合并两个数组并去除重复项只留一个的方法
- js实现prototype扩展的方法(字符串,日期,数组扩展)
- 用JS实现一个数组合并的方法(要求去重)
- JS实现合并两个数组并去除重复项只留一个的方法
- JS解析json数据并将json字符串转化为数组的实现方法
- Javascript 数组添加一个 indexOf 方法的实现代码
- 使用MVC中的HtmlHelper对象的ActionLink方法,实现一个Javascript:void(0)效果,去调用一个JS方法
- 用JS实现字符串转日期并比较大小的方法
- JS判断一个数组中是否有重复值的三种方法
- js:splice()方法(从一个数组中移除一个或多个元素)
- JS 实现 创建类、继承、方法添加、对象克隆、数组封装操作
- 给js的数组实现一个类似ruby的迭代器
- js 数组实现一个类似ruby的迭代器