JS数组根据某个字段进行分组
//1.找出数组中相同的元素
getRepeatNum(arr) { let obj = {}; for (let i = 0, len = arr.length; i < len; i++) { if (obj[arr[i]] == undefined) { obj[arr[i]] = 1; } else { obj[arr[i]]++; } } for (let key in obj) { obj[key] <= 1 && delete obj[key]; } return Object.keys(obj); },
//2.根据数组的某个参数进行分组
getGroupNum(arr) {
let newArry = {}; for (let i = 0; i < arr.length; i++) { if (newArry[arr[i].num.errcode]) { newArry[arr[i].num.errcode].push(arr[i].num.num) } else { newArry[arr[i].num.errcode] = [arr[i].num.num] } } return newArry },
变型:
getGroupNum(arr) { let newArry = {}; for (let i = 0; i < arr.length; i++) { const obj = { time:arr[i].statis_time, num:arr[i].num.num, }; if (newArry[arr[i].num.errcode]) { newArry[arr[i].num.errcode].push(obj) } else { newArry[arr[i].num.errcode] = [obj] } } return newArry },
遍历:数组或对象
let errcodeRepeat = this.getRepeatNum(errcode); let seriesData = this.getGroupNum(res.data.info); errcodeRepeat.map(item=>{//数组 series.push({ name:item, data:seriesData[item], type:'line', }) });
const seriesObj = this.getGroupNum(res.data.info); const xAxis = res.data.info.map(item => item.statis_time); // const xAxisGroup = []; const errcode = []; const series = []; Object.keys(seriesObj).map(key=>{//对象:key和obj(key) errcode.push(key); // const xAxisData = []; const seriesData = []; seriesObj[key].map(item=>{ // xAxisData.push(item.time); seriesData.push(item.num); }); // xAxisGroup.push({ // data:xAxisData, // }); series.push({ name:key, data:seriesData, type:'line', }); });
总结:
首先拿到的是一堆未分组的数组:[{...}];
其次根据某个字段进行分组等到:
1.对象:{key:[...]}
2.新数组:[
{ name:key,data:[]}
...
]
实现方法:
//数组变型得到新数组 arryGroupMatch(arr) { var map = {} var dest = [] for (var i = 0; i < arr.length; i++) { var ai = arr[i] if (!map[ai.errno]) { dest.push({ errno: ai.errno, data: [ai] }) map[ai.errno] = ai } else { for (var j = 0; j < dest.length; j++) { var dj = dest[j] if (dj.errno === ai.errno) { dj.data.push(ai) break } } } } return dest } // lodash插件方法: import _ from 'lodash' const oldArr = _.groupBy(arr, 'xxx');//对象 let newArr = [] Object.keys(oldArr).forEach(key=>{// 数组 newArr.push({name:key,data:oldArr[key]}) })