Created
August 23, 2012 22:19
-
-
Save nlf/3442706 to your computer and use it in GitHub Desktop.
check if array contents are unique
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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