【发布时间】:2020-01-25 02:50:08
【问题描述】:
我有以下源数组:
const list = [
{
students: [ 'peter', 'bob', 'john']
},
{
students: [ 'thomas', 'sarah', 'john']
},
{
students: [ 'john', 'sarah', 'jack']
}
];
我想得到唯一的学生姓名和他们的人数,最终结果应该是这样的:
{
'john': 3,
'sarah': 2,
'thomas': 1,
'jack': 1,
'peter': 1,
'bob': 1
}
这是我的尝试:
const unique = list.reduce(function(total, curr){
const students = curr.students;
for (c of students) {
if (!total[c]) {
total[c] = 1
} else {
total[c] += 1;
}
}
return total;
}, {});
有没有更好的方法呢?还是更快更清洁的方式?谢谢
【问题讨论】:
-
您的预期输出在对象中首先具有最常出现的名称 - 这是必需的吗? (有可能实现,只是要求有点奇怪,因为好的脚本可能不应该依赖于属性顺序)
-
是的,我也订购了
标签: javascript arrays for-loop ecmascript-6 reduce