Angular中如何依据对象数组排序嵌套数组内的id数组?
解决方法
要实现将secondObj中嵌套的ids数组按照firstObj排序后的id顺序排列(得到你期望的升序结果),可以通过以下步骤实现:
步骤1:创建ID到排序索引的映射
首先基于排序后的firstObj,建立每个id对应的排序位置索引映射,这样可以快速获取每个id的排序优先级:
// 假设firstObj已经通过你提供的代码完成排序 const idPriorityMap = new Map(); firstObj.forEach((item, index) => { idPriorityMap.set(item.id, index); });
步骤2:对secondObj的ids数组进行排序
利用上面的映射,对secondObj中的ids数组进行排序。由于你期望的结果是firstObj排序后的逆序(升序),所以在排序比较时交换两个ID的索引差:
// 遍历secondObj中的每个对象,对ids数组排序 secondObj.forEach(obj => { obj.ids.sort((idA, idB) => { // 比较两个ID在firstObj排序后的索引,逆序排列得到升序结果 return idPriorityMap.get(idB) - idPriorityMap.get(idA); }); });
完整代码示例
将两步整合后的完整代码如下:
// 你的初始数据 const firstObj = [{ id: "111", name: "one", type: "user" }, { id: "222", name: "two", type: "user" }, { id: "333", name: "three", type: "admin" }, { id: "444", name: "four", type: "user" }, { id: "555", name: "five", type: "user" }, { id: "666", name: "six", type: "admin" }]; const secondObj = [ { ids: ['333', '666', '555', '222'], name: "handlers" } ]; // 对firstObj进行降序排序(你已实现的代码) firstObj.sort((p1,p2) => (p1.id > p2.id)?-1:1); // 创建ID优先级映射 const idPriorityMap = new Map(); firstObj.forEach((item, index) => { idPriorityMap.set(item.id, index); }); // 排序secondObj的ids数组 secondObj.forEach(obj => { obj.ids.sort((idA, idB) => { return idPriorityMap.get(idB) - idPriorityMap.get(idA); }); }); console.log(secondObj); // 输出结果: // [ { ids: [ '222', '333', '555', '666' ], name: 'handlers' } ]
原理说明
- 通过
Map存储每个id在排序后firstObj中的索引,避免每次排序比较时都遍历firstObj,提升性能。 - 排序
ids数组时,通过比较两个id的索引值,调整排序方向来得到你需要的升序结果。如果需要和firstObj排序后的顺序一致(降序),只需将比较逻辑改为return idPriorityMap.get(idA) - idPriorityMap.get(idB)即可。
内容的提问来源于stack exchange,提问作者Nikunj Chaklasiya
相关产品推荐
相关产品推荐

