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);
5
  • 2
    Replace that loop with arr = Object.keys(set)
    – Raynos
    Commented Nov 7, 2011 at 4:12
  • FYI, Object.keys is new in ECMAScript 5, so it may not be available in all browsers (reference) Commented Nov 7, 2011 at 4:21
  • @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
    Commented Nov 7, 2011 at 5:24
  • @user686924: see developer.mozilla.org/en/JavaScript/Reference/Global_Objects/…
    – KooiInc
    Commented Nov 7, 2011 at 5:55
  • @user686924: I reverted back to my original solution, which doesn't use Object.keys Commented Nov 8, 2011 at 4:38
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.

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.