首页 > 解决方案 > JS 将一个数组元素推到最后

问题描述

我正在尝试重新排列数组的排序。假设我有以下结构

    const array = [{
     location: 'Table 2',
     data: {..}
    }, {
     location: 'Unassigned',
     data: {..}
    }, {
     location: 'Table 1',
     data: {..}
}
];

将“表 1”移动到索引 0、“表 2”紧随其后(对表 3、4 等保持相同的顺序)和“未分配”始终移动到最后的正确方法是什么。最好使用 lodash。

这是我到目前为止尝试过的

  forEach(allItemsSorted, (item, index) => {
    const total = allItemsSorted.length;
    let hasUnassigned = false;
    if (item.location === 'Unassigned') {
      allItemsSorted[total] = item;
      hasUnassigned = true;
    }
    if (hasUnassigned && index === total) {
      return;
    }
    allItemsSorted[index] = item;
  })

标签: javascriptecmascript-6lodash

解决方案


您可以为所需订单获取一个对象,为未知值获取一个默认值,以将这些项目移动到数组的末尾。

const
    array = [{ location: 'Table 2', data: {} }, { location: 'Unassigned', data: {} }, { location: 'Table 1', data: {} }],
    order = { 'Table 1': 1, 'Table 2': 2, default: Infinity };

array.sort(({ location: a }, { location: b }) =>
    (order[a] || order.default) - (order[b] || order.default));

console.log(array);
.as-console-wrapper { max-height: 100% !important; top: 0; }

对于仅'Unassigned'按升序排序到末尾和所有其他值,您也可以使用上面提到的 order 对象,但更改已知和未知字符串的值。

const
    array = [{ location: 'Table 2', data: {} }, { location: 'Unassigned', data: {} }, { location: 'Table 1', data: {} }],
    order = { Unassigned: 1 };

array.sort(({ location: a }, { location: b }) =>
    (order[a] || 0) - (order[b] || 0) || a.localeCompare(b));

console.log(array);
.as-console-wrapper { max-height: 100% !important; top: 0; }


推荐阅读