0

0

数组对象根据父子关系与显示优先级进行排序的通用方法

DDD

DDD

发布时间:2025-09-17 10:58:20

|

339人浏览过

|

来源于php中文网

原创

数组对象根据父子关系与显示优先级进行排序的通用方法

本文介绍如何对包含父子关系(通过id和reference_id关联)及显示优先级 (display_priority) 的数组对象进行排序。我们将构建一个分层结构,先处理父子归属,再根据优先级对父节点和子节点进行排序,最终展平为符合预期顺序的数组。

问题背景与挑战

前端后端数据处理中,我们经常会遇到需要对具有层级关系的数据进行排序的场景。例如,一个产品列表可能包含主产品和其关联的子产品,同时每个产品都有一个显示优先级。我们的目标是根据以下规则对一个扁平化数组进行重排序:

  1. 父子关系优先: 具有 reference_id 的项(子项)必须紧随其父项(id 与 reference_id 匹配的项)之后。
  2. 显示优先级排序: 在同一层级(例如,所有顶层项之间,或同一父项的所有子项之间),应根据 display_priority 字段进行升序排列

给定以下原始数据结构:

const originalData = [
  { id: 3, name: 'hello world', reference_id: null, display_priority: 10 },
  { id: 6, name: 'hello world', reference_id: 2, display_priority: 30 },
  { id: 1, name: 'hello world', reference_id: 2, display_priority: 40 },
  { id: 4, name: 'hello world', reference_id: null, display_priority: 80 },
  { id: 2, name: 'hello world', reference_id: null, display_priority: 100 },
  { id: 5, name: 'hello world', reference_id: 3, display_priority: 110 },
];

我们期望得到的输出顺序如下:

[
  { id: 3, name: 'hello world', reference_id: null, display_priority: 10 },
  { id: 5, name: 'hello world', reference_id: 3, display_priority: 110 }, // id:5 是 id:3 的子项
  { id: 4, name: 'hello world', reference_id: null, display_priority: 80 },
  { id: 2, name: 'hello world', reference_id: null, display_priority: 100 },
  { id: 6, name: 'hello world', reference_id: 2, display_priority: 30 }, // id:6 是 id:2 的子项
  { id: 1, name: 'hello world', reference_id: 2, display_priority: 40 }, // id:1 也是 id:2 的子项
];

可以看到,id: 3 作为父项,其 display_priority 为 10。其子项 id: 5 紧随其后。 然后是顶层项 id: 4 (priority 80),接着是 id: 2 (priority 100)。 id: 2 的子项 id: 6 (priority 30) 和 id: 1 (priority 40) 紧随其后,且它们之间按 display_priority 排序。

现有尝试及局限性分析

用户最初尝试使用 Array.prototype.reduce 方法来迭代并构建排序后的数组:

const reorderedArray = test.reduce((acc, current) => {
  const referenceId = current.reference_id;
  if (referenceId === null) {
    const referencedChildIndex = acc.findIndex(item => item.reference_id === current.id);
    if (referencedChildIndex !== -1) {
      acc.splice(referencedChildIndex, 0, current);
    } else {
      acc.push(current);
    }
  } else {
    const referencedIndex = acc.findIndex(item => item.id === referenceId);
    if (referencedIndex !== -1) {
      acc.splice(referencedIndex + 1, 0, current);
    } else {
      acc.push(current);
    }
  }
  return acc;
}, []);

这种方法的主要局限在于它高度依赖于原始数组中元素的顺序。如果父元素在原始数组中出现在其子元素之后,或者子元素在父元素之前被处理,findIndex 可能无法找到对应的父/子项,导致元素被错误地放置到数组末尾。此外,这种方法并未充分考虑 display_priority 的排序逻辑,仅侧重于父子关系的插入。对于更复杂的层级结构和多重排序条件,这种迭代插入的方式难以保证最终结果的正确性和效率。

核心思路与设计

为了可靠地解决这个问题,我们需要一个更结构化的方法,它将分三个主要阶段进行:构建ID映射表构建层级结构排序层级结构展平层级结构

步骤一:构建ID映射表

首先,创建一个哈希映射(Map 或对象),将每个元素的 id 作为键,元素本身作为值。这使得我们能够以 O(1) 的时间复杂度通过 id 快速查找任何元素,这在构建父子关系时非常有用。

步骤二:构建层级结构

遍历原始数组中的每个元素。对于每个元素,我们将其视为一个潜在的节点。如果一个元素的 reference_id 不为 null,则说明它是一个子节点,需要将其添加到其父节点的 children 数组中。同时,我们需要识别出所有 reference_id 为 null 的顶层节点。

步骤三:排序层级结构

一旦构建了树状的层级结构(每个父节点包含一个 children 数组),我们就需要对这些结构进行排序。这通常通过递归完成:

  1. 对子节点排序: 遍历每个父节点,将其 children 数组按照 display_priority 进行升序排序。
  2. 对顶层节点排序: 对所有 reference_id 为 null 的顶层节点数组也按照 display_priority 进行升序排序。

步骤四:展平层级结构

最后一步是将排序后的树状结构展平回一个一维数组。这可以通过深度优先遍历(DFS)的递归方式实现:

一览AI绘图
一览AI绘图

一览AI绘图是一览科技推出的AIGC作图工具,用AI灵感助力,轻松创作高品质图片

下载
  1. 遍历排序后的顶层节点。
  2. 对于每个顶层节点,将其添加到结果数组中。
  3. 如果该节点有子节点,则递归地对这些子节点执行相同的操作(先添加子节点本身,再处理其子节点),确保父节点在前,子节点紧随其后。

完整实现代码

下面是使用 JavaScript 实现上述思路的完整代码:

function reorderArrayByReferenceAndPriority(data) {
  // 1. 构建ID映射表,并为每个项添加一个空的children数组
  const itemMap = new Map();
  data.forEach(item => {
    // 创建一个副本,避免直接修改原始数据,并添加children属性
    itemMap.set(item.id, { ...item, children: [] });
  });

  const topLevelItems = [];

  // 2. 构建层级结构
  itemMap.forEach(item => {
    if (item.reference_id === null) {
      // 顶级项
      topLevelItems.push(item);
    } else {
      // 子项,尝试找到其父项
      const parent = itemMap.get(item.reference_id);
      if (parent) {
        parent.children.push(item);
      } else {
        // 如果找不到父项,将其视为顶级项(或根据业务需求处理,例如报错)
        topLevelItems.push(item);
        console.warn(`Item with id ${item.id} has reference_id ${item.reference_id}, but parent not found.`);
      }
    }
  });

  // 3. 排序层级结构
  // 递归函数,用于对子节点进行排序
  function sortChildren(node) {
    if (node.children && node.children.length > 0) {
      node.children.sort((a, b) => (a.display_priority || 0) - (b.display_priority || 0));
      node.children.forEach(child => sortChildren(child)); // 递归排序子节点的子节点
    }
  }

  // 对所有顶级项的子节点进行排序
  topLevelItems.forEach(item => sortChildren(item));

  // 对顶级项本身进行排序
  topLevelItems.sort((a, b) => (a.display_priority || 0) - (b.display_priority || 0));

  // 4. 展平层级结构
  const reorderedFlatArray = [];

  // 递归函数,用于展平树结构
  function flatten(node) {
    // 添加当前节点到结果数组中,但移除临时的children属性
    const { children, ...itemWithoutChildren } = node;
    reorderedFlatArray.push(itemWithoutChildren);

    if (children && children.length > 0) {
      children.forEach(child => flatten(child));
    }
  }

  // 遍历排序后的顶级项,并展平
  topLevelItems.forEach(item => flatten(item));

  return reorderedFlatArray;
}

// 原始数据
const originalData = [
  { id: 3, name: 'hello world', reference_id: null, display_priority: 10 },
  { id: 6, name: 'hello world', reference_id: 2, display_priority: 30 },
  { id: 1, name: 'hello world', reference_id: 2, display_priority: 40 },
  { id: 4, name: 'hello world', reference_id: null, display_priority: 80 },
  { id: 2, name: 'hello world', reference_id: null, display_priority: 100 },
  { id: 5, name: 'hello world', reference_id: 3, display_priority: 110 },
];

const reorderedResult = reorderArrayByReferenceAndPriority(originalData);
console.log(JSON.stringify(reorderedResult, null, 2));

输出结果:

[
  {
    "id": 3,
    "name": "hello world",
    "reference_id": null,
    "display_priority": 10
  },
  {
    "id": 5,
    "name": "hello world",
    "reference_id": 3,
    "display_priority": 110
  },
  {
    "id": 4,
    "name": "hello world",
    "reference_id": null,
    "display_priority": 80
  },
  {
    "id": 2,
    "name": "hello world",
    "reference_id": null,
    "display_priority": 100
  },
  {
    "id": 6,
    "name": "hello world",
    "reference_id": 2,
    "display_priority": 30
  },
  {
    "id": 1,
    "name": "hello world",
    "reference_id": 2,
    "display_priority": 40
  }
]

代码详解

  1. itemMap 的构建与初始化:

    • itemMap = new Map():创建了一个 Map 结构,用于存储以 id 为键、以对象为值的元素。
    • data.forEach(item => itemMap.set(item.id, { ...item, children: [] })):遍历原始数据。为了避免直接修改原始对象,我们使用 { ...item, children: [] } 创建了一个浅拷贝,并为每个对象添加了一个空的 children 数组。这个 children 数组将用于存储其子节点。
  2. 构建层级结构:

    • topLevelItems = []:用于收集所有 reference_id 为 null 的顶层项。
    • itemMap.forEach(item => { ... }):再次遍历 itemMap 中的所有项。
    • if (item.reference_id === null):如果 reference_id 为 null,说明它是顶层项,直接加入 topLevelItems 数组。
    • else { const parent = itemMap.get(item.reference_id); if (parent) { parent.children.push(item); } ... }:如果 reference_id 不为 null,则通过 itemMap.get(item.reference_id) 查找其父项。如果找到,就将当前项作为子项添加到父项的 children 数组中。如果找不到父项,则将其视为一个独立的顶层项(或根据业务需求进行错误处理),并发出警告。
  3. 排序层级结构:

    • sortChildren(node) 递归函数:
      • 它首先检查当前 node 是否有 children。
      • 如果有,就使用 sort 方法根据 display_priority 对 children 数组进行升序排序。a.display_priority || 0 的用法确保了即使 display_priority 字段缺失,也能有一个默认值(0)进行排序,避免 undefined 导致的问题。
      • 然后,它递归地对每个子节点调用 sortChildren,确保整个子树的 children 数组都被排序。
    • topLevelItems.forEach(item => sortChildren(item)):对所有顶层项调用 sortChildren,从而对整个树结构中的所有子节点进行排序。
    • topLevelItems.sort((a, b) => (a.display_priority || 0) - (b.display_priority || 0)):最后,对 topLevelItems 数组本身进行排序,以确定顶层项的最终顺序。
  4. 展平层级结构:

    • reorderedFlatArray = []:最终结果数组。
    • flatten(node) 递归函数:
      • const { children, ...itemWithoutChildren } = node;:使用解构赋值将 children 属性从当前节点中分离,并将剩余属性组成一个新的对象 itemWithoutChildren。这是为了在最终输出中不包含临时的 children 属性。
      • reorderedFlatArray.push(itemWithoutChildren);:将当前节点(不含 children 属性)添加到结果数组。
      • if (children && children.length > 0) { children.forEach(child => flatten(child)); }:如果当前节点有子节点,则递归地对每个子节点调用 flatten 函数。由于 children 数组已经排序,并且是深度优先遍历,这确保了父节点在前,其排序后的子节点紧随其后。
    • topLevelItems.forEach(item => flatten(item)):遍历排序后的顶层项,并调用 flatten 函数,从而将整个排序后的树结构展平为最终的一维数组。

注意事项

  • 循环引用: 当前方案不包含循环引用检测。如果数据中存在 A 引用 B,B 又引用 A 的情况,可能会导致无限递归。在实际应用中,需要根据业务需求增加循环引用检测或限制递归深度。
  • reference_id 不存在: 如果某个项的 reference_id 指向了一个不存在的 id,该项会被视为顶层项并发出警告。根据具体业务场景,可能需要更严格的错误处理,例如抛出异常或将其过滤掉。
  • display_priority 缺失: 代码中使用了 (a.display_priority || 0),这意味着如果 display_priority 字段缺失或为 null/undefined,它将被视为 0 进行排序。这是一种常见的默认处理方式,但如果业务有其他要求(例如,缺失的项排在最后),则需要调整排序逻辑。
  • 数据量: 对于非常庞大的数据集,构建 Map 和递归操作可能会消耗较多内存和计算资源。但在大多数常见场景下,这种方法是高效且可维护的。
  • 深拷贝与浅拷贝: 在构建 itemMap 时,我们对原始对象进行了浅拷贝 ({ ...item, children: [] })。这意味着原始对象中的嵌套对象仍然是引用。如果需要修改嵌套对象而不影响原始数据,则需要进行深拷贝。

总结

通过将扁平化数组转换为一个临时的树状结构,并结合 Map 进行高效查找、递归排序以及深度优先遍历展平,我们能够可靠地实现根据父子关系和显示优先级对数组对象进行排序的需求。这种方法结构清晰、逻辑严谨,能够有效应对复杂的层级和多重排序条件,是处理此类数据排序问题的通用且健壮的解决方案。

相关专题

更多
js获取数组长度的方法
js获取数组长度的方法

在js中,可以利用array对象的length属性来获取数组长度,该属性可设置或返回数组中元素的数目,只需要使用“array.length”语句即可返回表示数组对象的元素个数的数值,也就是长度值。php中文网还提供JavaScript数组的相关下载、相关课程等内容,供大家免费下载使用。

559

2023.06.20

js刷新当前页面
js刷新当前页面

js刷新当前页面的方法:1、reload方法,该方法强迫浏览器刷新当前页面,语法为“location.reload([bForceGet]) ”;2、replace方法,该方法通过指定URL替换当前缓存在历史里(客户端)的项目,因此当使用replace方法之后,不能通过“前进”和“后退”来访问已经被替换的URL,语法为“location.replace(URL) ”。php中文网为大家带来了js刷新当前页面的相关知识、以及相关文章等内容

436

2023.07.04

js四舍五入
js四舍五入

js四舍五入的方法:1、tofixed方法,可把 Number 四舍五入为指定小数位数的数字;2、round() 方法,可把一个数字舍入为最接近的整数。php中文网为大家带来了js四舍五入的相关知识、以及相关文章等内容

756

2023.07.04

js删除节点的方法
js删除节点的方法

js删除节点的方法有:1、removeChild()方法,用于从父节点中移除指定的子节点,它需要两个参数,第一个参数是要删除的子节点,第二个参数是父节点;2、parentNode.removeChild()方法,可以直接通过父节点调用来删除子节点;3、remove()方法,可以直接删除节点,而无需指定父节点;4、innerHTML属性,用于删除节点的内容。

479

2023.09.01

JavaScript转义字符
JavaScript转义字符

JavaScript中的转义字符是反斜杠和引号,可以在字符串中表示特殊字符或改变字符的含义。本专题为大家提供转义字符相关的文章、下载、课程内容,供大家免费下载体验。

534

2023.09.04

js生成随机数的方法
js生成随机数的方法

js生成随机数的方法有:1、使用random函数生成0-1之间的随机数;2、使用random函数和特定范围来生成随机整数;3、使用random函数和round函数生成0-99之间的随机整数;4、使用random函数和其他函数生成更复杂的随机数;5、使用random函数和其他函数生成范围内的随机小数;6、使用random函数和其他函数生成范围内的随机整数或小数。

1091

2023.09.04

如何启用JavaScript
如何启用JavaScript

JavaScript启用方法有内联脚本、内部脚本、外部脚本和异步加载。详细介绍:1、内联脚本是将JavaScript代码直接嵌入到HTML标签中;2、内部脚本是将JavaScript代码放置在HTML文件的`<script>`标签中;3、外部脚本是将JavaScript代码放置在一个独立的文件;4、外部脚本是将JavaScript代码放置在一个独立的文件。

659

2023.09.12

Js中Symbol类详解
Js中Symbol类详解

javascript中的Symbol数据类型是一种基本数据类型,用于表示独一无二的值。Symbol的特点:1、独一无二,每个Symbol值都是唯一的,不会与其他任何值相等;2、不可变性,Symbol值一旦创建,就不能修改或者重新赋值;3、隐藏性,Symbol值不会被隐式转换为其他类型;4、无法枚举,Symbol值作为对象的属性名时,默认是不可枚举的。

554

2023.09.20

c++ 根号
c++ 根号

本专题整合了c++根号相关教程,阅读专题下面的文章了解更多详细内容。

58

2026.01.23

热门下载

更多
网站特效
/
网站源码
/
网站素材
/
前端模板

精品课程

更多
相关推荐
/
热门推荐
/
最新课程
React 教程
React 教程

共58课时 | 4.1万人学习

TypeScript 教程
TypeScript 教程

共19课时 | 2.4万人学习

Bootstrap 5教程
Bootstrap 5教程

共46课时 | 3万人学习

关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送

Copyright 2014-2026 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号