Remove duplicates from JSON string
by toubia95
HTML
With Duplicates:<br/>
<textarea class="dirty">[{
"testada": "ecom",
"id": "27"
}, {
"testada": "alorta",
"id": "27"
}, {
"testada": "france24",
"id": "23"
}, {
"testada": "seloger",
"id": "23"
}]</textarea><br/>
<button class="process">Clean</button>
<br/>
Without Duplicates:<br/>
<textarea class="clean"></textarea>
CSS
textarea {
width:400px;
height:200px;
}
JavaScript
jQuery(".process").click( function() {
var dirty = JSON.parse( jQuery(".dirty").val().trim() );
var cleaned = removeDuplicates(dirty);
console.log(cleaned);
jQuery(".clean").val( JSON.stringify(cleaned) );
});
/*
* Function from http://stackoverflow.com/questions/21951115/remove-duplicate-values-from-json-data. Answered by Tushar Gupta
*/
function removeDuplicates(json_all) {
var arr = [],
collection = [];
$.each(json_all, function (index, value) {
if ($.inArray(value.halId_s, arr) == -1) {
arr.push(value.halId_s);
collection.push(value);
}
});
return collection;
}