javascript - 如何使用 map 函数创建一个数组同时排除重复值?

标签 javascript arrays

如何使用 map 函数创建一个数组同时排除重复值?

在我的应用中,我们创建了一个这样的数组

var commTypes;

commTypes = ourObject.map(function(obj, index) {
  return obj.section;
});

它创建一个 obj.sections 数组。 ourObject 中的许多对象具有相同的部分,我希望数组没有重复项。 有没有办法在 map 功能中做到这一点? 我已经尝试了几种在 map 函数中引用 commTypes 的方法,但都没有奏效。

最佳答案

你不能用 map 函数来做到这一点。 map 功能只是将一项转换为另一项(例如,只获取您需要的属性)。如果您想在创建数组的同时排除重复值,您应该使用哈希表(为了获得最佳性能)和循环/过滤功能。

使用过滤功能:

var hash = {};

var commTypes = ourObject.map(function(obj) {
  return obj.section;
}).filter(function(section){
    if(!hash[section]){
        hash[section] = true;
        return true;
    }

    return false;
});

Demo 1

使用 for 循环(单个 for 循环遍历初始数组):

var hash = {};
var commTypes = [];

for(var i = 0; i < ourObject.length; i++){
    var section = ourObject[i].section;

    if(!hash[section]){
        commTypes.push(section);
        hash[section] = true;
    }
}

Demo 2

关于javascript - 如何使用 map 函数创建一个数组同时排除重复值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29682113/

相关文章:

javascript - 无论是否附加了 Chrome 调试器,日期构造函数的工作方式都不同

javascript - iframe jquery 或 javascript 的刷新按钮

javascript - 使用 Angular JS 数据表在其中一列中添加 Jquery datepicker

arrays - 令人惊讶的数组扩展行为

javascript - AngularJS 使用 ng-repeat 迭代多层数组

ios - 从 Parse Server 接收字符串、数字和图像并将它们添加到本地数组

javascript - 在 Rails Controller 中,如何防止双重提交(当用户双击提交按钮或按两次回车时)?

javascript - 重命名 Typescript 文件

javascript - 使用 For 循环 JS 分配变量

java - 对在 Java 中跳过数字的整数数组进行分组