JSFiddle - React, Tailwind, and code Playground
JavaScript 1.7
var data = [{
"id": 0,
"children": [{
"id": 1,
"children": [{
"id": 2, // with my algorithm, this one get also flagged for deletion
}]
}, {
"id": 2, // remove this one
}, {
"id": 3,
}, {
"id": 4, // with my algorithm, this one get also flagged for deletion
"children": [{
"id": 5, // with my algorithm, this one get also flagged for deletion
"children": [{
"id": 6, // with my algorithm, this one get also flagged for deletion
}]
}]
}, {
"id": 5, // remove this one
"children": [{
"id": 6, // remove this one
}]
}, {
"id": 6, // remove this one
}, {
"id": 7,
}]
}];
/**
* Checks if the element is an empty object or array
*/
function checkForEmpty(el) {
return (angular.isObject(el) && Object.keys(el).length === 0) || (angular.isArray(el) && el.length == 0);
}
/**
* Walk through an object or array and remove duplicate elements where the 'id' key is duplicated
* Depends on a seenIds object (using it as a set)
*/
function processData(el) {
// If the element is an array...
if (angular.isArray(el)) {
for (var i = 0; i < el.length; i++) {
var value = el[i];
processData(value);
// If the child is now empty, remove it from the array
if (checkForEmpty(value)) {
el.splice(i, 1);
i--; // Fix index after splicing (http://stackoverflow.com/a/9882349/1370556)
}
}
}
// If the element is an object...
else if (angular.isObject(el)) {
for (var key in el) {
// Make sure the key is not part of the prototype chain
if (el.hasOwnProperty(key)) {
var value = el[key];
if (key == 'id') {
// If the key has been seen, remove it
if...