<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>jquery 数组按某一字段分组</title>
<!-- <script src="./Scripts/jquery-3.3.1.min.js"></script> -->
<script src="./Scripts/jquery-1.10.2.min.js"></script>
</head>
<body>
<script type="text/javascript">
$(function()
{
let a = null;
let aa = a?a:0;
console.log(aa);
let b = undefined;
let bb = b?b:0;
console.log(bb);
let c = '';
let cc = c?c:0;
console.log(cc);
list = [
{"name": "John", "Average": 15, "High": 10, "DtmStamp": 1358226000000},
{"name": "Jane", "Average": 16, "High": 92, "DtmStamp": 1358226000000},
{"name": "Jane", "Average": 17, "High": 45, "DtmStamp": 1358226000000},
{"name": "John", "Average": 18, "High": 87, "DtmStamp": 1358226000000},
{"name": "Jane", "Average": 15, "High": 10, "DtmStamp": 1358226060000},
{"name": "John", "Average": 16, "High": 87, "DtmStamp": 1358226060000},
{"name": "John", "Average": 17, "High": 45, "DtmStamp": 1358226060000},
{"name": "Jane", "Average": 18, "High": 92, "DtmStamp": 1358226060000}
];
const sorted =groupBy(list, function (item) {
return [item.name];//按照name进行分组
});
console.log(sorted);
})
function groupBy(array, f)
{
debugger;
const groups = {};
array.forEach(function (o) { //注意这里必须是forEach 大写
const group = JSON.stringify(f(o));
groups[group] = groups[group] || [];
groups[group].push(o);
});
return Object.keys(groups).map(function (group) {
return groups[group];
});
}
</script>
</body>
</html>
数组分组-按某一个字段分组
于 2021-06-28 16:51:04 首次发布