js 扁平化图数据结构
时间: 2023-10-07 17:05:22 浏览: 44
在 JavaScript 中,扁平化图数据结构可以使用对象或数组来表示。这里我给出两种常见的方式:
1. 使用对象表示扁平化图数据结构:
```javascript
const graph = {
A: ['B', 'C'], // 节点 A 与节点 B、C 相连
B: ['D'], // 节点 B 与节点 D 相连
C: [], // 节点 C 没有相邻节点
D: ['E'], // 节点 D 与节点 E 相连
E: [] // 节点 E 没有相邻节点
};
```
2. 使用数组表示扁平化图数据结构:
```javascript
const graph = [
{ node: 'A', edges: ['B', 'C'] }, // 节点 A 与节点 B、C 相连
{ node: 'B', edges: ['D'] }, // 节点 B 与节点 D 相连
{ node: 'C', edges: [] }, // 节点 C 没有相邻节点
{ node: 'D', edges: ['E'] }, // 节点 D 与节点 E 相连
{ node: 'E', edges: [] } // 节点 E 没有相邻节点
];
```
以上是两种常见的表示扁平化图数据结构的方式,你可以根据具体需求选择适合的方式来使用。
相关问题
扁平化数据转换树形结构
扁平化数据指的是将具有层级关系的数据展开成一维结构,而树形结构则是将具有层级关系的数据呈现为树状图。因此,将扁平化数据转换成树形结构需要进行一些处理。
以下是一个示例数据:
```json
[
{ "id": 1, "name": "节点1", "parentId": null },
{ "id": 2, "name": "节点2", "parentId": 1 },
{ "id": 3, "name": "节点3", "parentId": 2 },
{ "id": 4, "name": "节点4", "parentId": 2 },
{ "id": 5, "name": "节点5", "parentId": 1 },
{ "id": 6, "name": "节点6", "parentId": 5 }
]
```
其中,每个对象表示一个节点,`id`表示节点的唯一标识,`name`表示节点的名称,`parentId`表示节点的父节点标识。其中,根节点的`parentId`为`null`。
现在要将这个扁平化数据转换成树形结构,可以按照以下步骤进行:
1. 创建一个空的树形结构对象
2. 遍历扁平化数据,将每个节点加入树形结构中
3. 对于每个节点,如果它是根节点,则直接加入树形结构对象的`children`属性中,否则需要将它加入它的父节点的`children`属性中
以下是使用JavaScript实现的代码:
```javascript
function flatToTree(flatData) {
const tree = {};
const map = {};
for (const node of flatData) {
const id = node.id;
const parentId = node.parentId;
if (!map[id]) {
map[id] = { children: [] };
}
map[id].id = id;
map[id].name = node.name;
if (parentId === null) {
tree[id] = map[id];
} else {
if (!map[parentId]) {
map[parentId] = { children: [] };
}
map[parentId].children.push(map[id]);
}
}
return Object.values(tree);
}
```
使用该函数对示例数据进行转换,可以得到如下结果:
```json
[
{
"id": 1,
"name": "节点1",
"children": [
{
"id": 2,
"name": "节点2",
"children": [
{
"id": 3,
"name": "节点3",
"children": []
},
{
"id": 4,
"name": "节点4",
"children": []
}
]
},
{
"id": 5,
"name": "节点5",
"children": [
{
"id": 6,
"name": "节点6",
"children": []
}
]
}
]
}
]
```
可以看到,该函数将扁平化数据成功转换成了树形结构。
// js 将数组扁平化并去除其中重复数据,最终得到一个升序且不重复的数组 const arr= [[1,2,2], [3,4,5,5], [6,7,8,9,[11,12,[12,13,[14]]]], 10];
可以使用递归和 Set 数据结构来实现数组扁平化并去重。具体实现如下:
```javascript
function flattenAndSort(arr) {
const result = [];
arr.forEach(item => {
if (Array.isArray(item)) {
result.push(...flattenAndSort(item));
} else {
result.push(item);
}
});
return Array.from(new Set(result)).sort((a, b) => a - b);
}
const arr = [[1,2,2], [3,4,5,5], [6,7,8,9,[11,12,[12,13,[14]]]], 10];
const flattenedAndSortedArr = flattenAndSort(arr);
console.log(flattenedAndSortedArr); // [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]
```
首先定义一个 `flattenAndSort` 函数,用于将数组扁平化并排序。函数内部定义一个空数组 `result` 用于存储扁平化后的结果。然后遍历输入的数组 `arr`,对于每个元素,如果是数组,则递归调用 `flattenAndSort` 函数将其扁平化,否则直接将其添加到 `result` 中。
最后使用 `new Set(result)` 将结果去重,并调用 `Array.from` 将 Set 转换成数组,最后调用 `sort` 方法进行升序排序。最终得到一个升序且不重复的数组。