鉴于其排序值,我想找到一个方向。但是,我发现仅index不能完成我想要的。

给定排序功能,我只想根据其值确定一个项目是否实际上已移至另一个索引,而不是因为另一个项目已移动。

例:

const things = [
  { id: 't1', val: 4 }, // This moves to index 1, see T1 notes
  { id: 't2', val: 2 },
  { id: 't3', val: 5 }, // This moves to index 0
  { id: 't4', val: 1 },
  { id: 't5', val: 3 },
]

// Sort to highest vals first
let thingOrder = things.sort((a, b) => b.val - a.val)

thingOrder = thingOrder.map((thing, index) => {
  const oldIndex = things.indexOf(thing)

  if (index === oldIndex)
    thing.direction = 'same'
  else if (index > oldIndex)
    thing.direction = 'up'
  else if (index < oldIndex)
    thing.direction = 'down'

  return thing
})

console.log(thingOrder)


预期结果:

{ id: 't3', val: 5 }, // Up
{ id: 't1', val: 4 }, // Same
{ id: 't5', val: 3 }, // Same
{ id: 't2', val: 2 }, // Down
{ id: 't4', val: 1 }, // Down


T1注意:从技术上讲,标识为t1的项目已移至索引1,但这并不是因为其为val-而是因为T3已移至其上方。

如何实现发现某项在列表中是否真正上移或下移的目标?

最佳答案

根据这些评论,似乎在讨论移动的含义。我不确定这是什么意思(即使在评论之后)


  给定一个排序功能,我只想根据一个项目的值确定一个项目是否实际上已移至另一个索引,而不是因为另一个项目已移动


一项不会根据其值移动。它是根据其价值与周围人们的关系而移动的。

但是,如果您只是想比较项目从何处开始,您可以这样做。
使范围从零到数组的长度。然后根据数组的排序顺序对其进行排序。此排序范围将向您显示在哪里索引。



const things = [
    { id: 't1', val: 4 }, // This moves to index 1, see T1 notes
    { id: 't2', val: 2 },
    { id: 't3', val: 5 }, // This moves to index 0
    { id: 't4', val: 1 },
    { id: 't5', val: 3 },
  ]

// This is a simple range:
let sortOrder = Array.from(things, (_, i) => i)

// Sort it based on things
sortOrder.sort((a, b) => things[a].val - things[b].val )

console.log("sort order:", sortOrder)

// map to direction names
// by comparing index to current position
let directions = sortOrder.map((item, i) => {
    if (item > i) return "up"
    if (item < i) return "down"
    return "same"
})

console.log(directions)

07-26 00:18
查看更多