js分组方法

1.分组-得到一个二维数组

/** array-要分组的对象数组 name-分类标识 */
export const groupBy = (array: any[], name: string) => {
  const groups = {};
  array.forEach(function (o) {
    const group = JSON.stringify(o[name]);
    groups[group] = groups[group] || [];
    groups[group].push(o);
  });
  return Object.values(groups);
};

const name = 'source';
const links = [
  { source: 'test1', target: 'test1', value: 10 },
  { source: 'test1', target: 'test2', value: 30 },
  { source: 'test1', target: 'test3', value: 40 },
  { source: 'test2', target: 'test4', value: 20 },
  { source: 'test2', target: 'test4', value: 20 },
  { source: 'test2', target: 'test4', value: 20 },
];
const groupData = groupBy(links, name);
console.log(groupData);
// [
//   [
//     { source: 'test1', target: 'test1', value: 10 },
//     { source: 'test1', target: 'test2', value: 30 },
//     { source: 'test1', target: 'test3', value: 40 },
//   ],
//   [
//     { source: 'test2', target: 'test4', value: 20 },
//     { source: 'test2', target: 'test4', value: 20 },
//     { source: 'test2', target: 'test4', value: 20 },
//   ]
// ]

2.分组-得到一个数组对象

export const groupBy = (array: any[], name: string) => {
  const groups = {};
  array.forEach(function (o) {
    const group = JSON.stringify(o[name]);
    groups[group] = groups[group] || [];
    groups[group].push(o);
  });
  return groups;
};

const name = 'source';
const links = [
  { source: 'test1', target: 'test1', value: 10 },
  { source: 'test1', target: 'test2', value: 30 },
  { source: 'test1', target: 'test3', value: 40 },
  { source: 'test2', target: 'test4', value: 20 },
  { source: 'test2', target: 'test4', value: 20 },
  { source: 'test2', target: 'test4', value: 20 },
];
const groupData = groupBy(links, name);
console.log(groupData);
// {
//  'test1':[
//      { source: 'test1', target: 'test1', value: 10 },
//      { source: 'test1', target: 'test2', value: 30 },
//      { source: 'test1', target: 'test3', value: 40 },
//     ],
//  'test2':[
//      { source: 'test2', target: 'test4', value: 20 },
//      { source: 'test2', target: 'test4', value: 20 },
//      { source: 'test2', target: 'test4', value: 20 },
//     ]
// }

1 函数groupBy有两个形参,一为对象数组,二为指定分类方式的key;
2 groupBy函数内,先创建一个空对象;
3 然后forEach遍历对象数组,遍历时要执行的函数中只有一个形参o(数组中的每个元素);
4 由于下面函数调用是想用source来分组,因此let group = JSON.stringify( f(o) ),相当于先获取到对象数组list中的source属性对应的属性值并放入数组中:[‘test1’],然后再将属性值转换为json字符串:“[‘test1’]”;
5 groups[group] = groups[group] || [],在js中对象也是关联数组,因此这里相当于做了两件事,一是把group作为groups的key,二是将对应的value初始化,第一次执行为空数组,循环执行时找到相同的source时保持不变;
6 groups[group].push( o ),这句相当于把list中每个对象压入数组中作为value;
7 Object.values(groups)是取出groups对象中的所有values,返回分好了组的二维数组

你可能感兴趣的:(web基础,#,JavaScript,javascript,前端)