首页 > 解决方案 > 过滤数组以获取多个值并限制结果

问题描述

我有一个包含多个对象的数组:

export class Task {
  id: number;
  title: string;
  state: number;
  priority: number;
  desc: string;
  date: string;
  listid: string;
}

如何过滤此数组以获取最接近即将到来的日期的前五个任务?此外,对象的 date 可能为空 -如果没有至少 5 个带 dates 的任务,则剩余的任务量应替换为按优先级排序的任务(5 高 - 1 低)。

以下数组的 Fe(我忽略了不太重要的值)..

tasks = [
  { date: 19-07-2019, priority: 2 },
  { date: 21-07-2019, priority: 3 },
  { date: 20-07-2019, priority: 4 },
  { date: null, priority: 2 },
  { date: null, priority: 4 },
  { date: null, priority: 5 },
  { date: null, priority: 3 }
  ];

..我希望函数返回这个:

result = [
  { date: 19-07-2019, priority: 2 },
  { date: 20-07-2019, priority: 4 },
  { date: 21-07-2019, priority: 3 },
  { date: null, priority: 5 },
  { date: null, priority: 4 },
];

我已经尝试过找到出路,但这就是我所拥有的:

getFirstFiveTasks(): Observable<Task[]> {
    return of(this.tasks.filter(tasks => tasks.date > this.date));
}

但这仅返回具有即将到来的日期的任务,不将结果限制为 5 并且忽略优先级,以防有没有日期的任务。

标签: arraystypescript

解决方案


好吧,在这种情况下,您可以做几件事。我在 JavaScript 中创建了一个片段,因此将其转换为 typescript 应该不会很麻烦。

在所有这些之前,我确实必须更新您的Date字符串,因为我最初无法使用 解析它们Date.parse,但是,我假设您在代码中将日期作为真实日期,因此当我使用它时您可以忽略我的解析。

因此,要订购,根据超过 1 个标准,您可以订购如下:

function compareTasks( t1, t2 ) {
  // if dates are equal, priority wins
  if (t1.date === t2.date) {
    return t2.priority - t1.priority;
  }
  // if either is null, the other one wins
  if (t1.date === null && t2.date !== null) {
    return 1;
  }
  if (t1.date !== null && t2.date === null) {
    return -1;
  }
  // otherwise, the closest date wins
  return Date.parse(t1.date) - Date.parse(t2.date);
}

一旦你有了它,你只需对你的数组进行排序(先取一部分,所以你不会改变它),然后取前 n 个项目。

function orderBy( array, ordercb ) {
  // slice() creates a copy, then sorts on that copy, returning the ordered copy
  // there is no mutation of the input parameter
  return array.slice().sort( ordercb );
}

function take( array, count ) {
  // take the first count items
  return array.slice( 0, count );
}

const tasks = [
  { date: '2019-07-19', priority: 2 },
  { date: '2019-07-21', priority: 3 },
  { date: '2019-07-20', priority: 4 },
  { date: null, priority: 2 },
  { date: null, priority: 4 },
  { date: null, priority: 5 },
  { date: null, priority: 3 }
];

function orderBy( array, ordercb ) {
  return array.slice().sort( ordercb );
}

function take( array, count ) {
  return array.slice( 0, count );
}

function compareTasks( t1, t2 ) {
  if (t1.date === t2.date) {
    return t2.priority - t1.priority;
  }
  if (t1.date === null && t2.date !== null) {
    return 1;
  }
  if (t1.date !== null && t2.date === null) {
    return -1;
  }
  return Date.parse(t1.date) - Date.parse(t2.date);
}

console.log( take( orderBy( tasks, compareTasks ), 5 ) );


推荐阅读