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
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1742290127a4416032.html
评论列表(0条)