javascript - 对数组中的非后续元素进行排序

标签 javascript arrays algorithm sorting

我有一个项目列表,我希望它们根据字段 enqueuedAt 进行排序按降序排列。在属于同一队列的项目中(由 queueName 标识), position (最低的优先)应该优先于 enqueuedAt .

换句话说,整体排序顺序应该以enqueuedAt为准(降序),在内部,属于同一队列的项目在它们之间互换位置,因此具有较低 position 的项目总是排在更高的 position 之前.

为了实现这一点,我想出了下面的代码。有没有办法提高时间复杂度?

const data = [
  {
    id: 1,
    enqueuedAt: 8,
    queueName: 'Queue 1',
    position: 1
  },
  {
    id: 2,
    enqueuedAt: 7,
    queueName: 'Queue 2',
    position: 1
  },
  {
    id: 3,
    enqueuedAt: 6,
    queueName: 'Queue 3',
    position: 3
  },
  {
    id: 4,
    enqueuedAt: 5,
    queueName: 'Queue 4',
    position: 2
  },
  {
    id: 5,
    enqueuedAt: 1,
    queueName: 'Queue 1',
    position: 2
  },
  {
    id: 6,
    enqueuedAt: 2,
    queueName: 'Queue 4',
    position: 1
  },
  {
    id: 7,
    enqueuedAt: 4,
    queueName: 'Queue 1',
    position: 3
  },
  {
    id: 8,
    enqueuedAt: 3,
    queueName: 'Queue 2',
    position: 2
  }
]

function sortThem(array) {
  array.sort((a, b) => b.enqueuedAt - a.enqueuedAt)

  for (let i = 0; i < array.length - 1; i++) {
    for (let j = i + 1; j < array.length; j++) {
      if (array[i].queueName === array[j].queueName) {
        if (array[j].position < array[i].position) {
          const t = array[j]
          array[j] = array[i]
          array[i] = t
        }
      }
    }
  }

  return array
}

console.log(sortThem(data))

最佳答案

一个简短的方法可以

  • enqueuedAt排序数据,

  • queueName分组,

  • 将数组减少

    • 位置对任何组进行排序,
    • 在临时结果数组中的相同索引处获取所有项目,最后
  • 采用平面阵列。

const
    data = [{ id: 1, enqueuedAt: 8, queueName: 'Queue 1', position: 1 }, { id: 2, enqueuedAt: 7, queueName: 'Queue 2', position: 1 }, { id: 3, enqueuedAt: 6, queueName: 'Queue 3', position: 3 }, { id: 4, enqueuedAt: 5, queueName: 'Queue 4', position: 2 }, { id: 5, enqueuedAt: 1, queueName: 'Queue 1', position: 2 }, { id: 6, enqueuedAt: 2, queueName: 'Queue 4', position: 1 }, { id: 7, enqueuedAt: 4, queueName: 'Queue 1', position: 3 }, { id: 8, enqueuedAt: 3, queueName: 'Queue 2', position: 2 }],
    result = Object
        .values(data
            .sort((a, b) => b.enqueuedAt - a.enqueuedAt)
            .reduce((r, o) => ((r[o.queueName] ??= []).push(o), r), {})
        )
        .reduce((r, array) => (array
            .sort((a, b) => a.position - b.position)
            .forEach((o, i) => (r[i] ??= []).push(o)),
            r
        ), [])
        .flat();

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

关于javascript - 对数组中的非后续元素进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65178967/

相关文章:

javascript - float div - 可变高度和可变列 - 没有间隙

javascript - "CALL "C :\Program Files\nodejs\\node. exe“错误

用于处理数组的 Javascript

c++ - 以递归方式检查每个橄榄球比分,不重复

c# - 根据条件合并 IEnumerable 中的元素

algorithm - 动态规划 - 硬币

javascript - 为什么我们需要 isPrototypeOf 呢?

javascript - 脚本加载 jquery 中的代码不起作用

python - 使用 Numpy 进行交易

java - 使用日期对 String[] 进行排序