1

I have an array like this:

var data = [
            { Group: 'A', Name: 'SD' },
            { Group: 'B', Name: 'FI' },
            { Group: 'A', Name: 'MM' },            
            { Group: 'B', Name: 'CO' }
           ];

I want to get only the unique Group values in an array like:

var unique = ['A','B'];

I looked at some of the examples on SO but I don't understand them. Can anyone tell me how I should do this?

2 Answers 2

2
var data = [
             { Group: 'A', Name: 'SD' },
             { Group: 'B', Name: 'FI' },
             { Group: 'A', Name: 'MM' },            
             { Group: 'B', Name: 'CO' }
           ];

var set = {};
for (var i = 0; i < data.length; i++)
    set[data[i].Group] = 1;

var arr = [];
for(var key in set)
    arr.push(key);

alert(arr);
Sign up to request clarification or add additional context in comments.

5 Comments

Replace that loop with arr = Object.keys(set)
FYI, Object.keys is new in ECMAScript 5, so it may not be available in all browsers (reference)
@PetarIvanov This works great in IE9. As per Cheran's FYI, this will not work in IE < 9. Any suggestion on how I should this without Object.keys() ?
@user686924: I reverted back to my original solution, which doesn't use Object.keys
0

If you are using ES6/ES2015 or later you can do it this way:

var unique = [...new Set(data.map(item => item.Group))];

Here is an example on how to do it.

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.