Skip to content

Instantly share code, notes, and snippets.

@ajcrites
Created April 7, 2015 17:55
Show Gist options
  • Save ajcrites/505b8be9a5a3d795ba05 to your computer and use it in GitHub Desktop.
Save ajcrites/505b8be9a5a3d795ba05 to your computer and use it in GitHub Desktop.
var uniqueByProp = require("./unique-by-prop"),
assert = require("assert");
describe('Unique by prop', function () {
it('filter values based on identical property', function () {
var arr = [{x: 1}, {x: 1}, {x: 2}];
assert.deepEqual(uniqueByProp(arr, 'x'), [{x: 1}, {x: 2}]);
});
it('filter values based on identical property in the presence of other properties', function () {
var arr = [{x: 1, y: 1}, {x: 1, y: 2}, {x: 2, y: 3}];
assert.deepEqual(uniqueByProp(arr, 'x'), [{x: 1, y: 1}, {x: 2, y: 3}]);
});
});
/**
* Function that filters an array of objects by checking duplicates of
* a particular property. For example
*
* [{x: 1}, {x: 1}, {x: 2}]
*
* We can use this function (array, 'x') to get back
* [{x: 1}, {x: 2}]
*/
module.exports = function (array, property) {
var foundHash = {};
return array.filter(function (item) {
var prop = item[property];
// we already found a matching item with this property
if (foundHash[prop]) {
// filters out
return false;
}
// did not find an item with this property yet, so we record it
foundHash[prop] = true;
// keeps
return true;
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment