【问题标题】:Specific sort items of an array数组的特定排序项
【发布时间】:2020-11-15 22:37:09
【问题描述】:

假设我有一个包含 3 个项目的数组,它们是随机创建的。其中一个具有流行的布尔值:true,而其余的则没有。 我想把热门商品作为索引 1(居中) 像这样[例子,流行,例子]

我试着这样排序

 items.sort((a, b) => {
   if (a.id < b.id) {
     return -1;
   }
   if (a.id > b.id) {
     return 1;
   }
   return 0;
 });

但在这种情况下,我必须在所有这 3 个项目中添加特定 ID(从 1 到 3) 出于某种原因,我不能给他们 ID,所以这个解决方案不能按需要工作。

【问题讨论】:

  • 您可以将find true 项目和splice 设置为index = 1 而不是sort
  • 总是3个项目吗?可以有多个true 项目吗?排序肯定看起来有点矫枉过正
  • @slappy 总是 3 个项目,随机创建。
  • @YevgenGorbunkov 这个数组在服务器上生成
  • 如果只有三个,那么它只是一个索引交换。就像true 位于索引0 一样,它将是:[items[0], items[1]] = [items[1], items[0]]

标签: javascript function sorting indexing replace


【解决方案1】:

由于它总是三项,只需迭代数组,找到true 一项,并将其索引与索引1 交换。

const items = [
  {x: false},
  {x: false},
  {x: true},
];

for (const [i, o] of items.entries()) {
  if (o.x) {
    [items[i], items[1]] = [items[1], items[i]];
    break;
  }
}

console.log(items);

或者因为实际上只有两种可能性,你可以不使用循环。

const items = [
  {x: false},
  {x: false},
  {x: true},
];

var idx = items[0].x ? 0 :
          items[2].x ? 2 :
                       1;

[items[idx], items[1]] = [items[1], items[idx]];

console.log(items);

【讨论】:

    【解决方案2】:

    在排序器中检查popular,如果其中一个具有真正的布尔值,则使用适当的返回,否则根据id返回。

    data.sort((a, b) => {
      if (a.popular || b.popular) {
        return a.popular ? -1 : 1;
      }
      return a.id - b.id;
    });
    
    console.log(data)
    <script>
    const data = [
      {id:4},
      {id:2},
      {id:3,  popular:true},
      {id:1}
    ]
    </script>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-02-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-02-21
      • 2020-12-10
      • 1970-01-01
      相关资源
      最近更新 更多