admin管理员组文章数量:1332389
How do i use the map function to create an array while excluding duplicate values?
In my app we create an array like this
var mTypes;
mTypes = ourObject.map(function(obj, index) {
return obj.section;
});
It creates an array of obj.sections. Many of the objects in ourObject have the same section and i'd like the array to not have duplicates. Is there a way i can do that within the map function?
I've tried several ways of referencing mTypes
inside of the map function, but none have worked.
How do i use the map function to create an array while excluding duplicate values?
In my app we create an array like this
var mTypes;
mTypes = ourObject.map(function(obj, index) {
return obj.section;
});
It creates an array of obj.sections. Many of the objects in ourObject have the same section and i'd like the array to not have duplicates. Is there a way i can do that within the map function?
I've tried several ways of referencing mTypes
inside of the map function, but none have worked.
3 Answers
Reset to default 3You can't do this with map function. The map function just transform one item to another (e.g. take only properties you need). If you want to create array while excluding duplicate values you should use hashtables (for best performance) and for loop/filter function.
Using filter function:
var hash = {};
var mTypes = ourObject.map(function(obj) {
return obj.section;
}).filter(function(section){
if(!hash[section]){
hash[section] = true;
return true;
}
return false;
});
Demo 1
Using for loop (single for loop throught the initial array):
var hash = {};
var mTypes = [];
for(var i = 0; i < ourObject.length; i++){
var section = ourObject[i].section;
if(!hash[section]){
mTypes.push(section);
hash[section] = true;
}
}
Demo 2
The .map()
function is intended to give back a list with the same length as the original. Trying to do anything else is painful.
Thankfully there's the more general .reduce()
:
mTypes = ourObject.reduce(function(rv, obj) {
if (!rv.sections(obj.section)) {
rv.list.push(obj); // or just obj.section if that's all you want
rv.sections[obj.section] = 1;
}
return rv;
}, { list: [], sections: {} }).list;
That just remembers the section names in an object. (If your section id isn't a string, things get more involved; you'd maybe want to use an ES6 Set instead of a simple object.)
You can use any of this
[...new Set(array)];
array.filter((item, index) => array.indexOf(item) === index);
array.reduce(
(unique, item) => (unique.includes(item) ? unique : [...unique, item]),
[],
);
My favorite is using Set cause it’s the shortest and simplest
版权声明:本文标题:javascript - How do i use the map function to create an array while excluding duplicate values? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742290127a2447640.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论