You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何按OfficeID从IOfficeInfo数组中选取元素并推入新数组?

Fixing the OfficeInfo Sorting and Selection Issue

Let's break down what's causing your topoffice to be undefined and fix the overall logic of your function:

Key Problems in Your Current Code

  1. find returns undefined: This happens either because there's no element in data with an OfficeID matching this.OfficeID, or there's a type mismatch (e.g., this.OfficeID is a string but OfficeID is defined as a number in your type).
  2. Incorrect logic order: You're sorting the original data array first, which modifies it in-place, then trying to find your target element. Plus, you're not adding the remaining sorted elements to your return array.
  3. Unsafe push: If topoffice is undefined, calling push will throw an error.
  4. String-based date comparison: Comparing DateSubmitted as strings works for ISO 8601 formats (like YYYY-MM-DD), but it's unreliable for other date formats. Converting to Date objects is safer.

Corrected Code

Here's the revised function that addresses all these issues:

sortOfficeInfo(data: IOfficeInfo[]): IOfficeInfo[] {
  // First, separate the target office and remaining elements
  const targetOffice = data.find(item => item.OfficeID === this.OfficeID);
  const remainingOffices = data.filter(item => item.OfficeID !== this.OfficeID);

  // Sort remaining offices by DateSubmitted (convert to Date for reliable comparison)
  remainingOffices.sort((a, b) => {
    const dateA = new Date(a.DateSubmitted);
    const dateB = new Date(b.DateSubmitted);
    return dateA.getTime() - dateB.getTime();
  });

  // Build the return array: start with target (if exists), then add sorted remaining
  const result: IOfficeInfo[] = [];
  if (targetOffice) {
    result.push(targetOffice);
  }
  result.push(...remainingOffices);

  return result;
}

Additional Checks to Fix targetOffice Being undefined

  • Verify that this.OfficeID is a number (matching the OfficeID type in IOfficeInfo). If it's coming from user input or a string source, convert it with Number(this.OfficeID) first.
  • Double-check that your data array actually contains an element with the OfficeID value stored in this.OfficeID (you can log this.OfficeID and data to confirm).

内容的提问来源于stack exchange,提问作者John

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 04:06:26