Skip to content

Instantly share code, notes, and snippets.

@nlf
Created August 23, 2012 22:19
Show Gist options
  • Save nlf/3442706 to your computer and use it in GitHub Desktop.
Save nlf/3442706 to your computer and use it in GitHub Desktop.
check if array contents are unique
function _isUnique(array) {
function _sort(item) {
if (!item || typeof item !== 'object' || Array.isArray(item)) {
return item;
}
var result = [];
Object.keys(item).sort().forEach(function (key) {
result.push({ key: key, value: _sort(item[key]) });
});
return result;
}
function _uniques(array) {
var seen = [];
return array.filter(function (item) {
var encoded = JSON.stringify(_sort(item));
if (!~seen.indexOf(encoded)) {
seen.push(encoded);
return true;
}
});
}
array = _sort(array);
return JSON.stringify(array) === JSON.stringify(_uniques(array));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment