Last active
September 30, 2023 03:17
-
-
Save mnikn/6e243c185723c7900af7f089df42773a to your computer and use it in GitHub Desktop.
[array] array utils #utils
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| function duplicate(arr){ | |
| let set = new Set(); | |
| let result = []; | |
| for(let i = 0;i < arr.length; ++i) { | |
| if(!set.has(arr[i])) result.push(arr[i]); | |
| set.add(arr[i]); | |
| } | |
| return result; | |
| } | |
| // flat list to tree, eg: | |
| // [{id:1, parentId: 0}, {id: 2, parentId: 1}, {id: 3, parentId: 0}, {id: 4, parentId: 2}] => | |
| // [{id:1, parentId: 0, children: [{id: 2, parentId: 1, children: [{id: 4, parentId: 2}]}]}, {id: 3, parentId: 0}] | |
| function flatToTree(arr, idProp, parentIdProp, childrenProp = 'children'){ | |
| function flatItemToTree(arr, item) { | |
| let subItems = arr.filter(subitem => subitem[parentIdProp] === item[idProp]); | |
| subItems.forEach(subitem => isIter.add(subitem[idProp])); | |
| let subTrees = subItems.map(item => flatItemToTree(arr, item)); | |
| return Object.assign({}, item, {[childrenProp]: subTrees}); | |
| } | |
| if (!idProp || !parentIdProp) return arr; | |
| let isIter = new Set(); | |
| let result = []; | |
| arr.forEach(item => { | |
| let id = item[idProp]; | |
| if (!isIter.has(id)) { | |
| result.push(flatItemToTree(arr, item)); | |
| } | |
| }); | |
| return result; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment