lodash - 你将如何使用 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 文件的好方法,我会很乐意上传它们
解决方案
推荐阅读
- c++ - 如何在 C++ 中将矩阵与文件结合起来?
- r - 循环不匹配手动方式
- sql - SQL SERVER:(性能问题)获取所有行,如果列重复,则从 select 语句中选择另一列的最大行
- oracle - Oracle 中的动态 SQL 存储过程
- javascript - Javascript 无法识别相对路径导入
- swift - UITextField 不能成为 UITableView 中的第一响应者
- python - 如何使我的输出打印为“+”字母出现在列表中的次数?
- amazon-web-services - 终止 AWS Elastic Beanstalk 环境并删除数据库
- java - ParquetWriter 无法运行程序“chmod”
- ruby-on-rails - Spree 状态机在生产模式下缺少回调