如果您要记录来自代码段 1 的 final
数组,这就是输出(图像 1)
我想要做的是将我的数组减少到类似于图像2中显示的数组
我已经尝试使用 lodash _.uniqBy()
[Snippet 2],但仍然是我从日志记录中获得的输出 reduce
变量仍然是 Image 1 的输出。如何将我的 final
数组缩减为 Image 2 中的输出?
图像 2
const reduce = final.reduce((x, y) => {
if (x.department !== y.department) {
return x;
}
})
console.log(final)
console.log(reduce);
代码段 1
_.uniqBy(final, 'department')
代码片段 2
更新
这是在 TypeScript .ts
中,而不是在 .js
中。
接口(interface) => [{ 部门:字符串,教授:字符串[] }]
至于请求
这是我获取数据的地方
[
{
department: 'Department of Mathematics - INTRAMUROS',
professors: [
'Sabino, Lilibeth D.',
'Department Chair',
.....
这是我从 final
数组到达之前的代码
const recommend = [];
const final = [];
recommended.forEach((prof) => {
const find = proffessorDetails.find((collection) => {
return collection.professors.find((professor) => professor == prof);
});
recommend.push(find);
})
const find = recommend.map((collection) => {
return {
department: collection.department,
prof: _.intersection(collection.professors, recommended)
};
});
final.push(find);
最佳答案
最好使用 Map
来实现此目的:
type department = { department: string, professors: string[] };
let mUnique : Map<string, department> = new Map(final.map((obj: department) => <[string, department]>[obj.department, obj]));
let mUniqueArray = [...mUnique.values()]; //or Array.from(mUnique.values());
关于javascript - ES6的reduce方法没有返回期望的输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46586879/