Skip to content

Instantly share code, notes, and snippets.

@ritch
Created July 22, 2011 16:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ritch/1099788 to your computer and use it in GitHub Desktop.
Save ritch/1099788 to your computer and use it in GitHub Desktop.
var ex = [
{id: 1, name: 'blah'},
{id: 2, name: 'blah'},
{id: 3, name: 'blah'},
{id: 3, name: 'blah'},
{id: 3, name: 'blah'},
{id: 3, name: 'blah'},
{id: 4, name: 'blah'}
]
var objectifier = {
toObject: function(array, key) {
var i = 0
, o = {}
, l = array.length;
for(i; i < l; i++) {
o[key ? array[i][key] : i] = array[i];
}
return o;
},
toArray: function(object) {
var i = 0
, a = []
, key;
for(key in object) {
a.push(object[key]);
}
return a;
},
uniques: function(array, key) {
return this.toArray(this.toObject(array, key));
}
};
console.log(objectifier.uniques(ex, 'id'));
// outputs:
// [ { id: 1, name: 'blah' },
// { id: 2, name: 'blah' },
// { id: 3, name: 'blah' },
// { id: 4, name: 'blah' } ]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment