You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React中如何根据数组内Id与reference_id重新排序数组列表

React数组排序:父项紧跟对应子项的实现

问题描述

现有数组:

[
  { id: 1, name: 'hello world', reference_id: null },
  { id: 2, name: 'hello world', reference_id: null },
  { id: 3, name: 'hello world', reference_id: 1 },
  { id: 4, name: 'hello world', reference_id: null },
  { id: 5, name: 'hello world', reference_id: 1 },
  { id: 6, name: 'hello world', reference_id: 2 },
]

需要重排为:

[
  { id: 1, name: 'hello world', reference_id: null },
  { id: 3, name: 'hello world', reference_id: 1 },
  { id: 5, name: 'hello world', reference_id: 1 },
  { id: 2, name: 'hello world', reference_id: null },
  { id: 6, name: 'hello world', reference_id: 2 },
  { id: 4, name: 'hello world', reference_id: null },
]

核心需求是:每个reference_id为null的「父项」后面,紧跟所有reference_id等于该父项id的「子项」,父项保持原数组中的出现顺序,无对应子项的父项直接放在后续位置。

原代码错误原因

你写的第一行代码逻辑完全错误:

const parentIndex = skus?.findIndex(item => item.id === item.reference_id);

父项的reference_id是null,而item.id是数字类型,item.id === item.reference_id永远为false,导致parentIndex始终返回-1,后续的if判断逻辑根本不会触发,这就是代码"执行完第一行就停止"的直接原因。

正确解决方案

我们可以将数组拆分为父项和子项两组,再按父项顺序拼接对应子项,逻辑清晰且易维护:

// 原始数组
const skus = [
  { id: 1, name: 'hello world', reference_id: null },
  { id: 2, name: 'hello world', reference_id: null },
  { id: 3, name: 'hello world', reference_id: 1 },
  { id: 4, name: 'hello world', reference_id: null },
  { id: 5, name: 'hello world', reference_id: 1 },
  { id: 6, name: 'hello world', reference_id: 2 },
];

// 1. 拆分父项(reference_id为null)和子项(reference_id不为null)
const parentItems = skus.filter(item => item.reference_id === null);
const childItems = skus.filter(item => item.reference_id !== null);

// 2. 构建排序后的数组
const sortedSkus = [];
parentItems.forEach(parent => {
  // 添加当前父项
  sortedSkus.push(parent);
  // 添加所有属于该父项的子项
  const matchedChildren = childItems.filter(child => child.reference_id === parent.id);
  sortedSkus.push(...matchedChildren);
});

console.log(sortedSkus); // 输出目标排序结果

额外优化(可选)

如果需要子项按id升序排列,可以在筛选子项后添加排序逻辑:

const matchedChildren = childItems
  .filter(child => child.reference_id === parent.id)
  .sort((a, b) => a.id - b.id);

内容的提问来源于stack exchange,提问作者rasif sahl

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.21 20:43:00