通过内部数组对象中的键值对对象的外部数组进行排序

时间:2019-10-04 23:29:24

标签: javascript

我有一个对象数组,并且它在obj的另一个数组中,如何根据内部数组中相等的actionId键对该数组进行排序?

这是我的原始数组:

const arrayOfItems = {
    items: [
        {
            item: '1',
            anotherArray: [{ actionId: '1234-dh4t-tr21-6sw8' }]
        },
        {
            item: '2',
            anotherArray: []
        },
        {
            item: '3',
            anotherArray: []
        },
        {
            item: '4',
            anotherArray: [{ actionId: '1234-dh4t-tr21-6sw8' }]
        },
        {
            item: '5',
            anotherArray: []
        },
        {
            item: '6',
            anotherArray: [{ actionId: '1234-dh4t-tr21-6sw8' }]
        }
    ]
};

结果应该是彼此之间具有相同 actionId

的所有项目
sortedArray = {
    items: [
    {
       item: '1',
       anotherArray: [{ actionId: '1234-dh4t-tr21-6sw8' }]
    },
    {
      item: '4',
      anotherArray: [{ actionId: '1234-dh4t-tr21-6sw8' }]
    },
    {
      item: '6',
      anotherArray: [{ actionId: '1234-dh4t-tr21-6sw8' }]
    },
    ...
]
};

这是我尝试过的:

const sortingArray = arrayOfItems.items.sort((a, b) => {
  return a.anotherArray > 0 && a.anotherArray[0].actionId.localeCompare(b.anotherArray[0].actionId);
})

1 个答案:

答案 0 :(得分:1)

这样的事情可以解决问题。排序基于 ActionId ,然后是 item 。没有 actionId 的项目将被移到数组的末尾。

const arrayOfItems = {items: [{item: '1', anotherArray: [{actionId: '1234-dh4t-tr21-6sw8'}]}, {item: '2', anotherArray: []}, {item: '3', anotherArray: []}, {item: '4', anotherArray: [{actionId: '1234-dh4t-tr21-6sw8'}]}, {item: '5', anotherArray: []}, {item: '6', anotherArray: [{actionId: '1234-dh4t-tr21-6sw8'}]}]};

arrayOfItems.items.sort((a, b) => {
  const lenA = a.anotherArray.length,
        lenB = b.anotherArray.length;

  // order based on item if both a and b don't have an actionId
  if (!lenA && !lenB) return a.item - b.item;
  // move the element without actionId towards the end if a or b doesn't have an actionId
  if (!lenA || !lenB) return lenB - lenA;

  const actionIdA = a.anotherArray[0].actionId,
        actionIdB = b.anotherArray[0].actionId;

  // order based on item if both a and b have the same actionId
  if (actionIdA === actionIdA) return a.item - b.item;

  // order based on actionId
  return actionIdA.localeCompare(actionIdB);
});

console.log(arrayOfItems.items);

如果您不关心按 item 排序,则可以删除:

// order based on item if both a and b don't have an actionId
if (!lenA && !lenB) return a.item - b.item;

并且:

// order based on item if both a and b have the same actionId
if (actionIdA === actionIdA) return a.item - b.item;