JavaScript 数组对象排序:根据 preId 和 nextId 属性进行分组
思路:
首先,对原数组进行遍历,将每个 list 数组中的对象按照 preId 和 nextId 的关系进行排序。然后,从排序后的第一个对象开始,按照 nextId 的顺序向后遍历,将遍历到的对象加入一个临时数组中,并将 outerId 设置为遍历过程中第一个对象的 id。如果遍历到的对象的 nextId 为空,说明已经到了该组的最后一个对象,将该临时数组加入到输出数组中。如果遍历结束后仍有未加入输出数组的临时数组,说明存在多组有前后关系的对象,需要继续进行遍历和输出。
代码实现如下:
const originalArray = [
{
id: 1,
list: [
{
preId: '',
nextId: '',
id: 'N1',
},
],
},
{
id: 2,
list: [
{
preId: 'N4',
nextId: '',
id: 'N2',
},
],
},
{
id: 3,
list: [
{
preId: '',
nextId: 'N6',
id: 'N3',
},
],
},
{
id: 4,
list: [
{
preId: 'N6',
nextId: 'N2',
id: 'N4',
},
],
},
{
id: 5,
list: [
{
preId: '',
nextId: '',
id: 'N5',
},
],
},
{
id: 6,
list: [
{
preId: 'N3',
nextId: 'N4',
id: 'N6',
},
],
},
];
const sortedArray = [];
for (let i = 0; i < originalArray.length; i++) {
const currentList = originalArray[i].list;
// 对每个 list 数组进行排序
currentList.sort((a, b) => {
if (a.preId === '' && b.preId !== '') {
return -1;
} else if (a.preId !== '' && b.preId === '') {
return 1;
} else {
return 0;
}
});
// 从排序后的第一个对象开始遍历
let j = 0;
while (j < currentList.length) {
const currentObject = currentList[j];
const tempArray = [];
tempArray.push(currentObject);
tempArray[0].outerId = originalArray[i].id;
// 按照 nextId 的顺序向后遍历
while (currentObject.nextId !== '') {
const nextIndex = currentList.findIndex(item => item.id === currentObject.nextId);
if (nextIndex !== -1) {
currentObject = currentList[nextIndex];
tempArray.push(currentObject);
tempArray[tempArray.length - 1].outerId = originalArray[i].id;
} else {
break;
}
}
sortedArray.push({ id: originalArray[i].id, list: tempArray });
j += tempArray.length;
}
}
console.log(sortedArray);
该代码首先对原数组的每个 list 数组进行排序,然后遍历每个 list 数组,按照 nextId 的顺序将具有前后关系的对象加入一个临时数组中,并记录 outerId。最后将所有临时数组加入到输出数组中。
希望以上内容对您有所帮助。如果您还有其他问题,请随时提问。
注意: 以上代码仅供参考,您需要根据自己的实际需求进行调整和完善。
相关主题:
- JavaScript 数组排序
- JavaScript 对象
- 算法
- 数据结构
原文地址: https://www.cveoy.top/t/topic/otzU 著作权归作者所有。请勿转载和采集!