Filter Duplicates in JSON Array Of Objects
I come across a scenario where my JSON array of object returns some thousands of objects in which I should identify the duplicates, and eliminate it so that my JSON object array must have unique entries.
To resolve it I written one smart function , this takes the JSON Array of objects and eliminates the duplicates and returns the JSON array of unique objects.
The beauty is it’s a client side JavaScript function.
<script language="javascript" type="text/javascript">
function returnMeUniqueJSONArray(obj) {
var uniques = [];
var stringify = {};
for (var i = 0; i < obj.length; i++) {
var keys = Object.keys(obj[i]);
keys.sort(function (a, b) { return a - b });
var str = '';
for (var j = 0; j < keys.length; j++) {
if (j == 3 || j == 8) {
//I need to compare fields at (postion3) & (postion8) , both should not be unique, if you want to compare entire object then remove this if condition
str += JSON.stringify(keys[j]);
str += JSON.stringify(obj[i][keys[j]]);
}
}
if (!stringify.hasOwnProperty(str)) {
uniques.push(obj[i]);
stringify[str] = true;
}
}
return uniques;
}
</script>
Usage:
var actualJSONArrayWithDuplicates = jsonArrayOfObjects;
var actualJSONArrayWithOutDuplicates = returnMeUniqueJSONArray(jsonArrayOfObjects);
actualJSONArrayWithDuplicates is the Json array of Objects with unique records..
Hope you benefited…
No comments:
Post a Comment