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