【问题标题】:Dealing with null values position when sorting an array based on numeric values根据数值对数组进行排序时处理空值位置
【发布时间】:2021-10-05 11:18:20
【问题描述】:

StackBlitz example

Angular 应用程序。我正在将一个数组排序为*ngFor,以循环遍历结果以按排序顺序显示。

所以问题不只是简单的按数值排序。我有一个数组中的用户列表。每个用户都有一个数字值的sortId,这很简单。例如

this.users.sort((a, b) => a.sortId - b.sortId);

这会给我这样的结果:

Row 1 - Sort ID: null - original array position: 7
Row 2 - Sort ID: 1 - original array position: 4
Row 3 - Sort ID: 2 - original array position: 1
Row 4 - Sort ID: 3 - original array position: 3
Row 5 - Sort ID: 4 - original array position: 6
Row 6 - Sort ID: 5 - original array position: 8
Row 7 - Sort ID: 6 - original array position: 5
Row 8 - Sort ID: 7 - original array position: 2

但是,我想通过跳过它们来处理 null 值,保持它们在原始数组的位置 - 所以上面的 null 将在第 7 行(因为它的原始数组位置是 7) ,无论是否已经有 7 个 sortIdSortId: 7 将进入第 8 行。

预期结果:

Row 1 - Sort ID: 1 - original array position: 4
Row 2 - Sort ID: 2 - original array position: 1
Row 3 - Sort ID: 3 - original array position: 3
Row 4 - Sort ID: 4 - original array position: 6
Row 5 - Sort ID: 5 - original array position: 8
Row 6 - Sort ID: 6 - original array position: 5
Row 7 - Sort ID: null - original array position: 7
Row 8 - Sort ID: 7 - original array position: 2

用户字段:(arrayPosition 属性只是为了演示而添加的,所以不能使用。)

  users = [
    {
      user: 'fred',
      arrayPosition: 1,
      sortId: 2
    },
    {
      user: 'Gen',
      arrayPosition: 2,
      sortId: 7
    },
    {
      user: 'Billy',
      arrayPosition: 3,
      sortId: 3
    },
    {
      user: 'Sid',
      arrayPosition: 4,
      sortId: 1
    },
    {
      user: 'James',
      arrayPosition: 5,
      sortId: 6
    },
    {
      user: 'Tom',
      arrayPosition: 6,
      sortId: 4
    },
    {
      user: 'Jim',
      arrayPosition: 7,
      sortId: null
    },
    {
      user: 'Steve',
      arrayPosition: 8,
      sortId: 5
    }
  ];

只有当 sortId 低于原始数组位置时,它才能工作,否则它会出现故障:

  this.users.forEach(x => {
    this.fieldsList.splice(x['sortId'] - 1, 0, x);
  });

请帮我看看stackBlitz example

【问题讨论】:

  • 也许是一种过滤原始列表的解决方案,删除空项,对过滤后的列表进行排序,然后将该排序后的列表合并回原始列表中的非空索引。

标签: javascript arrays angular sorting object


【解决方案1】:

通过对所有非 null 值进行排序,然后在正确的索引中添加 null 来解决此问题

this.fieldsList = this.users
  .filter(x => x.sortId)
  .sort((a, b) => a.sortId - b.sortId);

this.users.forEach((x, i) => {
  if (x.sortId === null) this.fieldsList.splice(i, 0, x);
});

https://stackblitz.com/edit/sorting-n2gfvg?file=src/app/app.component.ts

【讨论】:

  • 需要把我的两个逻辑加在一起!谢谢
  • 您会注意到,除了两个排序值 2 和 5 之外,所有值都是空值。它们应该位于位置 2 和 5。因此,如果排序 id 小于空值索引值,那么排序 id 应该优先
  • 哦,我明白了,将尝试找到解决方案并更新答案
猜你喜欢
  • 2023-03-31
  • 2015-12-09
  • 1970-01-01
  • 1970-01-01
  • 2013-05-14
  • 1970-01-01
  • 2015-04-08
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多