Skip to content

Instantly share code, notes, and snippets.

@wyattdanger
Created June 28, 2011 15:49
Show Gist options
  • Save wyattdanger/1051446 to your computer and use it in GitHub Desktop.
Save wyattdanger/1051446 to your computer and use it in GitHub Desktop.
uniquify an array of objects on some key
function uniquifyOn(arr, fn) {
var returnArr = [],
tempArr = [];
arr.forEach(function (item) {
var key = fn(item);
if ( tempArr.indexOf(key) === -1) {
returnArr.push(item);
tempArr.push(key);
}
});
return returnArr;
}
// Example Usage
var cities = [{name: 'Austin', index: 0},{name: 'Chattanooga', index: 1},{name: 'Austin', index: 2},{name: 'Atlanta', index: 3}];
console.log(uniquifyOn(cities, function (item) {
return item.name;
}));
// returns
// [ { name: 'Austin', index: 0 },
// { name: 'Chattanooga', index: 1 },
// { name: 'Atlanta', index: 3 } ]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment