let numberSet = [1,2,3,5,2,5,1,2,3,1,4,1,1,2,5,5,6];
function distinct( arr ){
let result = [];
if( Array.isArray(arr) ){
let mappedSet = arr.reduce( (map, item)=>{
map[item] = true;
return map;
}, {} );
for( let key in mappedSet ){
result.push( key );
}
}
return result;
}
function constructNode( value, depth, targets ){
return {
value : value,
children : targets.filter(i=>i!==value).map(constructNode)
}
}
function constructTree( targets ){
let rootNode = {
value : null,
children : []
}
if( Array.isArray( targets ) && targets.length > 0 ){
rootNode.children = numberSet.map( (item, index, arr )=>{
return constructNode( item, index, arr );
});
}
return rootNode;
}
let rootNode = constructTree( distinct(numberSet) );
console.log( "Root Node, ", JSON.stringify(rootNode, null, 2 ) );