【问题标题】:JS Pushing one array element to the endJS 将一个数组元素推到最后
【发布时间】:2019-04-02 04:14:35
【问题描述】:

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

    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;
  })

【问题讨论】:

  • 为什么不使用sort

标签: javascript ecmascript-6 lodash


【解决方案1】:

这个怎么样

var data1 = [{location:'Table 2', data: {}}, {location: 'Unassigned', data: {}}, {location: 'Table 1', data: {}}, {location: 'Table 12', data: {}}, {location: 'Table 22', data: {}}, {location: 'Unassigned', data: {}}];

data.sort((a,b)=> a.location > b.location).filter(item => item.location != 'Unassigned').push([...data.filter(item => item.location == 'Unassigned')]);

结果

[{
"location": "Table 1",
"data": {}
},
{
"location": "Table 12",
"data": {}
},
{
"location": "Table 2",
"data": {}
},
{
"location": "Table 22",
"data": {}
},
{
"location": "Unassigned",
"data": {}
},
{
"location": "Unassigned",
"data": {}
}]

【讨论】:

    【解决方案2】:

    您可以为想要的顺序取一个对象,为未知值取一个默认值,以便将这些项目移动到数组的末尾。

    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; }

    【讨论】:

      【解决方案3】:

      如果你想重新排列一个数组,总是寻找 Array.sort 方法。使用自定义添加创建新数组只会造成困难。

      你可以试试这样的:

      • 创建一个接受location 并返回数值的函数。
      • 使用此值按您希望的任何顺序进行排序。

      const array = [
        {location:'Table 2', data: {}},
        {location: 'Unassigned', data: {}},
        {location: 'Table 1', data: {}},
        {location: 'Table 11', data: {}},
        {location: 'Table 31', data: {}},
        {location: 'Table 3', data: {}},
      ];
      
      array.sort(function(a,b) {
        return getSortValue(a.location) - getSortValue(b.location);
      });
      
      function getSortValue(location) {
        return location === 'Unassigned' ? Number.MAX_SAFE_INTEGER : location.match(/\d+/)[0];
      }
      
      console.log(array)

      【讨论】:

      • 注意:如果您觉得此答案有问题或遗漏了什么,请在评论中与您的投票一起分享您的观点。谢谢!
      【解决方案4】:

      如果您有以Table 开头的location 值并且未分配具有Unassigned 作为值,那么如何对array 进行排序。将适用于这种情况。但请注意其他值,除非它们是您想要的结果。

      const array = [{location:'Table 2', data: {}}, {location: 'Unassigned', data: {}}, {location: 'Table 1', data: {}}];
      array.sort(function(a,b){
        return a.location.localeCompare(b.location);
      });
      console.log(array);

      【讨论】:

        【解决方案5】:

        您可以使用Array.sort() - 始终将Unassigned 移动到末尾(两个ifs)。使用String.localeCompare()numeric option 对其他项目进行排序。

        注意:我使用array spread - [...array] - 来克隆数组,因此原始数组不会发生变异。如果要更改原始数组,可以跳过它。

        const array = [{location:'Table 27'}, {location:'Table 2'}, {location: 'Unassigned'}, {location: 'Table 11'}];
        
        const result = [...array].sort(({ location: a }, { location: b }) => {
          if(a === 'Unassigned') return 1;
          if(b === 'Unassigned') return -1;
          
          return a.localeCompare(b, undefined, {numeric: true});
        });
        
        console.log(result);

        【讨论】:

          猜你喜欢
          • 2014-11-05
          • 1970-01-01
          • 1970-01-01
          • 2023-01-16
          • 2017-12-14
          • 1970-01-01
          • 2021-03-14
          • 1970-01-01
          • 2013-01-21
          相关资源
          最近更新 更多