使用lodash / Javascript对班级进行分组并对用户进行计数

时间:2019-03-20 22:09:19

标签: javascript jquery lodash

得到一个数组列表,其中包含参加课程和用户的列表;需要一个输出,通过分组课程并计算总用户数来显示参加的用户;

var arrList = [
  { class: 'one', user: 'user1' },
  { class: 'two', user: 'user1' },
  { class: 'two', user: 'user2' },
  { class: 'one', user: 'user3' },
  { class: 'two', user: 'user3' },
  { class: 'three', user: 'user1' },
  { class: 'four', user: 'user1' }
];

// output
[
  { class: 'one', user: [ 'user1', 'user2', 'user3' ], count: 3 },
  { class: 'two', user: [ 'user1', 'user3' ], count: 2 },
  { class: 'three', user: [ 'user1' ], count: 1 },
  { class: 'four', user: [ 'user1' ], count: 1 } 
];

1 个答案:

答案 0 :(得分:2)

使用_.groupBy()通过class键收集对象,然后映射到所需的表单。

具有链接的解决方案(需要完全导入lodash软件包):

const arrList = [{"class":"one","user":"user1"},{"class":"two","user":"user1"},{"class":"two","user":"user2"},{"class":"one","user":"user3"},{"class":"two","user":"user3"},{"class":"three","user":"user1"},{"class":"four","user":"user1"}];

const result = _(arrList)
  .groupBy('class')
  .map((group, key) => ({
    class: key,
    user: _.map(group, 'user'),
    count: group.length
  }))
  .value();
  
console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.js"></script>

使用_.flow()的解决方案(可以从lodash包中导入所需的内容):

const { flow, partialRight: pr, groupBy, map } = _; // replace with imports in your project

const fn = flow(
  pr(groupBy, 'class'),
  pr(map, (group, key) => ({
    class: key,
    user: map(group, 'user'),
    count: group.length
  }))
);
  
const arrList = [{"class":"one","user":"user1"},{"class":"two","user":"user1"},{"class":"two","user":"user2"},{"class":"one","user":"user3"},{"class":"two","user":"user3"},{"class":"three","user":"user1"},{"class":"four","user":"user1"}];

const result = fn(arrList);
  
console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.js"></script>