js分組(group by)
阿新 • • 發佈:2019-01-08
對資料進行分組,類似sql的groupBy。
原理:遍歷陣列,將符合條件的資料放在一起,最後返回一個分組後的二維陣列。
//分組
export const groupBy = (list, fn) => {
const groups = {};
list.forEach(function (o) {
const group = JSON.stringify(fn(o));
groups[group] = groups[group] || [];
groups[group].push(o);
});
// return Object.keys(groups).map(function (group) {
// return groups[group];
// });
return groups;
}
list:原始資料。
fn:分組條件判斷函式,之後會根據該函式返回的結果進行分組,其有一個引數表示陣列的某一項資料。
示例:
let links = [
{ source: 'test1', target: 'test1', value: 10 },
{ source: 'test1', target: 'test2', value: 30 },
{ source: 'test1', target: 'test3', value: 40 },
{ source: 'test1', target: 'test4', value: 20 }
]
let groupData = groupBy(links, (link) => {
return link.source
})
console.log(groupData)
// 返回結果
//{
// "test1":[
// { source: "test1", target: "test1", value: 10 },
// { source: "test1", target: "test2", value: 30 },
// { source: "test1", target: "test3", value: 40 },
// { source: "test1", target: "test4", value: 20 }
// ]
// }