Test name | Executions per second |
---|---|
@john36allTa | 191.8 Ops/sec |
@dimoff66 | 116.1 Ops/sec |
@Bavashi | 90.9 Ops/sec |
var arr = [];
var len = 1000;
function init() {
for (var i = 0; i < len; i++) {
arr.push({
id: i+1,
name: i+" ...",
parent: i
});
}}
init();
function pack( data ){
const childs = id =>
data.filter( item => item.parent === id )
.map(
({id,name}) => ({id,name, children: childs(id)})
).map(
({id,name,children}) => children.length ? {id,name, children} : { id, name }
);
return childs(0);
}
const res = pack(arr)
function pack( arr ) {
const map = Object.assign({} , arr.map(v =>
({ [v.id]: Object.assign(v, { children: [] }) })
))
const tree = Object.values(map).filter(v =>
!(v.parent && map[v.parent].children.push(v))
)
return tree
}
const res = pack(arr)
function makeTree(array, parent) {
var tree = {};
parent = typeof parent !== 'undefined' ? parent : {id: 0};
var childrenArr = array.filter(function(child) {
return child.parent == parent.id;
});
if (childrenArr.length > 0) {
var childrenObj = {};
childrenArr.forEach(function(child) {
childrenObj[child.id] = child;
});
if (parent.id == 0) {
tree = childrenObj;
} else {
parent.children = childrenObj;
}
childrenArr.forEach(function(child) {
makeTree(array, child);
})
}
return tree;
};
const res = makeTree(arr);