js操作数组分类
var aa = [ { id: 1, imei: '', store_name: '合肥店' }, { id: 3, imei: '3', store_name: '合肥店' }, { id: 2, imei: '1', store_name: '芜湖店' }, { id: 4, imei: '34343', store_name: '上海店' } ];
分类 一 var list = aa, flag = 0, data = []; for(var i = 0; i< list.length; i++) { var az = ''; for (var j = 0; j < data.length; j++) { if(data[j][0].store_name == list[i].store_name) { flag = 1; az = j; break; } } if(flag == 1){ data[az].push(list[i]); flag = 0; } else if (flag == 0) { wdy = new Array(); wdy.push(list[i]); data.push(wdy); } } console.log(data)
分类二 for(var i = 0; i < list.length; i++) { if(!data[list[i].store_name]) { var arr = []; arr.push(list[i]); data[list[i].store_name] = arr; }else { data[list[i].store_name].push(list[i]) } } console.log(data);
结果如下:
分类三 var moth = [], flag = 0, list = aa; var wdy = { title: '', sur_name: '' } for (var i = 0; i < list.length; i++) { var az = ''; for (var j = 0; j < moth.length; j++) { if (moth[j].title == list[i]['store_name']) { flag = 1; az = j; break; } } if (flag == 1) { var ab = moth[az]; ab.sur_name.push(list[i]); flag = 0; } else if (flag == 0) { wdy = {}; wdy.title = list[i]['store_name']; wdy.sur_name = new Array(); wdy.sur_name.push(list[i]); moth.push(wdy); } } console.log(moth);