首页 > 解决方案 > 你将如何使用 Lodash 编写联合查找函数?

问题描述

我有一组脱节的数据,我需要通过 ID 将其压缩,类似于https://en.wikipedia.org/wiki/Disjoint-set_data_structure#Applications

如果我的数据是这样的......

[
 [
   {id:1},{id:2}
 ],[
   {id:2},{id:1},{id:3}
 ],[
   {id:3},{id:2}
 ],[
   {id:4}
 ]
]

编写将 id 匹配在一起并消除重复条目的 Union-Find 函数的最佳方法是什么?

最终结果应该是这样的......

[
[
    {id:1},{id:2},{id:3}
],
[
    {id:4}
]]

这是我到目前为止所得到的......我觉得我很接近但我错过了一些东西......

        fs.writeFileSync(`tempArray.json`,JSON.stringify(testarray))
    let newArray = []
    testarray.forEach(chain=>{
        if(_.includes(newArray,chain[0])){
            let index = _.indexOf(chain[0])
            chain.forEach(object=>{
                if(!_.includes(newArray[index],object)){
                    newArray[index].push(object)
                }
            })
        }
        else{
            let newArrayEntry = []
            chain.forEach(object=>{
                console.log(newArray)
                console.log(object)
                if(newArray.length>0){
                    newArray.forEach(arrchain=>{
                        if(!_.includes(arrchain,object)){
                            if(!_.includes(newArrayEntry,object)){
                                newArrayEntry.push(object)

                            }
                        }
                        
                    })
                }else{
                    console.log('else')
                    newArrayEntry.push(object)
                }
        
            })
            if(newArrayEntry.length>0){
                newArray.push(newArrayEntry)
            }
        }
    })
    fs.writeFileSync(`finalArray.json`,JSON.stringify(newArray))

这段代码基本上只是写了相同的结果......带有欺骗性。有什么想法吗?

如果有人知道我可以发送 json 文件的好方法,我会很乐意上传它们

标签: lodash

解决方案


推荐阅读