ScrollMap.js
我的所有数组都是树,一个节点只能属于一个父节点。 我想将list1与list2合并并获取resultList。我尝试了很多方法,递归回调,字符串搜索&替换等等,但我仍然无法理解。
答案 0 :(得分:2)
如果我理解正确,您希望 id 紧凑。
function getCompactById(arr) { // must have the same id
var res = [];
var obj = {};
obj.id = arr[0][0].id;
obj.children = [];
for(var i = 0; i < arr.length; i += 1) {
obj.children.push(arr[i][0].children[0]);
}
res.push(obj);
return res;
}
数组看起来像var arr = [list1, list2];
在函数创建一个数组和一个对象。该对象获取一个id和一个数组。 id始终相同,因此我们从第一个数组中获取它。遍历数组并推送所有对象arr[i][0].children[0]
。循环后按下数组中的obj。返回结果数组。
答案 1 :(得分:0)
以下代码将合并两个树数组的所有级别,而不仅仅是最高级别:
Option Strict On
Option Infer Off
Module Module1
Function ArrayEquals(a As Array, b As Array) As Boolean
If a Is Nothing AndAlso b Is Nothing Then
Return True
End If
If a Is Nothing OrElse b Is Nothing Then
Return False
End If
If a.Length <> b.Length Then
Return False
End If
For i As Integer = 0 To a.GetUpperBound(0)
If Not a.GetValue(i).Equals(b.GetValue(i)) Then
Return False
End If
Next
Return True
End Function
Sub Main()
'Dim a As Array = {"a", "b", "c"}
'Dim b As Array = {"d", "e", "f"}
'Dim c As Array = {"g", "h", "i"}
Dim a As Array = {1, 2, 3}
Dim b As Array = {2, 3, 1}
Dim c As Array = {3, 1, 2}
Dim x As Array = {a, b, c}
'Dim toFind As Array = {"d", "e", "f"}
Dim toFind As Array = {2, 3, 1}
Dim p As Object = Array.Find(CType(x, Object()), Function(z) ArrayEquals(CType(z, Array), toFind))
If p Is Nothing Then
Console.WriteLine("Not found.")
Else
' Visualize the result:
Select Case p.GetType().ToString()
Case Is = "System.Int32[]"
Dim q As Int32() = DirectCast(p, Int32())
Console.WriteLine(String.Join(", ", q))
Case Is = "System.String[]"
Dim q As String() = DirectCast(p, String())
Console.WriteLine(String.Join(", ", q))
End Select
End If
Console.ReadLine()
End Sub
End Module
查看JSBin上的代码:http://jsbin.com/wikaricita/3/edit?js,output
请注意,此算法的复杂度为O(n ^ 2),这意味着它不能很好地扩展。如果树木变大或性能是一个关键问题,您可能想要研究解决此问题的其他方法。