javascript - ES6的reduce方法没有返回期望的输出

标签 javascript typescript ecmascript-6

如果您要记录来自代码段 1final 数组,这就是输出(图像 1)

我想要做的是将我的数组减少到类似于图像2中显示的数组

我已经尝试使用 lodash _.uniqBy() [Snippet 2],但仍然是我从日志记录中获得的输出 reduce 变量仍然是 Image 1 的输出。如何将我的 final 数组缩减为 Image 2 中的输出?

enter image description here 图片 1

enter image description here

图像 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/

相关文章:

javascript - 基于像素距离的水平滚动事件

javascript - 如何通过在javascript中搜索多个属性值来逐个筛选?

javascript - nodejs中的CSV导出问题

angular - 使用 DomSanitizer 后,图片网址仍然不安全

angular - VSCode IntelliSense 不会建议 Angular 模块,除非在项目中手动导入

javascript - 可拖动的 div 应避免 x 和 y 重叠

javascript - 当 ES6 中存在结构相似性时,减少分配对象属性的冗余

javascript - 平移/缩放 d3.js 图表中新添加的点

javascript - 如何用包含升序字符串化数字的对象填充数组?

javascript - JS SocketIO 单例