Skip to content

Instantly share code, notes, and snippets.

@buzzdecafe
Last active December 16, 2015 05:59
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 buzzdecafe/5388594 to your computer and use it in GitHub Desktop.
Save buzzdecafe/5388594 to your computer and use it in GitHub Desktop.
dedupe an array of objects
// Paul's clean-up
function deDupe(dupeCheck, list) {
return list.reduce(function (prev, curr) {
if (!dupeCheck(curr, prev)) {
prev.push(curr);
}
return prev;
}, []);
}
deDupe(function (curr, prev) {
return prev.some(function (elm) {
return curr.x.y === elm.x.y;
});
}, xs);
var xs = [
{x: {y: 1}},
{x: {y: 2}},
{x: {y: 3}},
{x: {y: 4}},
{x: {y: 1}},
{x: {y: 4}},
{x: {y: 5}},
{x: {y: 6}}
];
// this is what the developer has to write:
function hasDupe(x, xs) {
return !!xs.filter(function(elem) {
return elem.x.y === x.x.y;
}).length;
}
// this is the generic function:
function dedupe(fn, arr) {
if (!arr) return [];
return arr.filter(function(elem, idx) {
return !fn(elem, arr.slice(idx + 1));
});
}
// Paul's abstraction:
function createDupeCheck(filter) {
return function dupeCheck(head, tail) {
return !!tail.filter(filter(head)).length;
};
}
dedupe(createDupeCheck(function (head) {
return function(elm, i, arr) {
return head.x.y === elm.x.y;
};
}), xs);
function dedupe(pred, list) {
function reducer(acc, curr) {
if (!acc.some(function(accElem) { return pred(accElem, curr); })) {
acc.push(curr);
}
return acc;
}
return (Array.isArray(list)) ? list.reduce(reducer, []) : function(ls) { return ls.reduce(reducer, []); };
}
dedupe(function (a, b) { return a.x.y === b.x.y; }, xs);
function dedupe(pred, list) {
function reducer(acc, curr) {
if (!acc.some(function(accElem) { return pred(accElem, curr); })) {
acc.push(curr);
}
return acc;
}
return list.reduce(reducer, []);
}
dedupe(function (a, b) { return a.x.y === b.x.y; }, xs);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment