【问题标题】:Sorting an array of objects -> if key comes later in the array, change order对对象数组进行排序 -> 如果键出现在数组的后面,则更改顺序
【发布时间】:2023-01-18 18:06:24
【问题描述】:

假设我有这个对象数组:

let arrOfObjs = [
{
    "id": "unique1",
    "parentId": "unique3", // So this one is equal to arrOfObjs[2].id
    "title": "title1"
}, 
{
    "id": "unique2",
    "parentId": "unique3", // This one is also equal to arrOfObjs[2].id
    "title": "title2"
}, 
{
    "id": "unique3",
    "parentId": "",
    "title": "title3"
}
]

情况是:

  • id 始终是唯一的

  • parentId 不是唯一的。 parentId 等于其中一个对象中的 id 之一

我想要实现的目标:

id 应该总是比数组中的 parentId 早。在上面的示例中,前两个对象包含'唯一'(3d 对象的 id)作为 parentId。那不应该发生。

所以应该这样排序:

let arrOfObjs = [
{
    "id": "unique3",
    "parentId": "",
    "title": "title3"
}
{
    "id": "unique2",
    "parentId": "unique3", 
    "title": "title2"
}, 
{
    "id": "unique1",
    "parentId": "unique3",
    "title": "title1"
}
]

所以根据对象的parentId,它应该找到等于parentId的id,当具有该id的对象的索引更高时,该对象应该排在第一位。

有点难以解释,但我希望它很清楚,如果您有任何问题,请告诉我

还没有尝试过任何东西,不知道我怎么能做到这一点。

【问题讨论】:

  • 身份证号码是多少?或者它是字符串?

标签: javascript


【解决方案1】:

尝试这个:

  arrOfObjs.sort((a, b) => {
  let aIndex = arrOfObjs.findIndex(obj => obj.id === a.parentId);
  let bIndex = arrOfObjs.findIndex(obj => obj.id === b.parentId);
  return aIndex - bIndex;
});

【讨论】:

  • 这不能正确排序数组
  • 他放弃了排序的数组,所以我只看那个数组并得到解决方案/
【解决方案2】:

这个比较器函数应该工作:

  • 如果aparentIdbid相同,则将a放在b之后。
  • 如果aidbparentId相同,则将a放在b之前。
  • 在所有其他情况下,保持顺序不变。

const array = [{
    "id": "unique1",
    "parentId": "unique3",
    "title": "title1"
}, {
    "id": "unique2",
    "parentId": "unique3",
    "title": "title2"
}, {
    "id": "unique3",
    "parentId": "",
    "title": "title3"
}];

array.sort((a, b) => a.parentId === b.id ? 1 : a.id === b.parentId ? -1 : 0);

console.log(array);

【讨论】:

    【解决方案3】:

    您可以存储所有id的位置并按parentId排序。

    const
        data = [{ id: "unique1", parentId: "unique3", title: "title1" }, { id: "unique2", parentId: "unique3", title: "title2" }, { id: "unique3", parentId: "", title: "title3" }],
        order = Object.fromEntries(data.map(({ id }, i) => [id, i + 1]));
    
    data.sort((a, b) => (order[a.parentId] || 0) - (order[b.parentId] || 0));
    
    console.log(data);
    .as-console-wrapper { max-height: 100% !important; top: 0; }

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-07-11
      • 2019-03-28
      • 2019-06-15
      • 1970-01-01
      • 1970-01-01
      • 2018-07-07
      • 1970-01-01
      相关资源
      最近更新 更多