3

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 commTypes;

commTypes = 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 commTypes inside of the map function, but none have worked.

3 Answers 3

3

You 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 commTypes = 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 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

Sign up to request clarification or add additional context in comments.

Comments

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():

commTypes = 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.)

1 Comment

@ScottKaye thanks - I'm not quite there yet but I'm going to start baking the cake anyway :)
2

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.