如何按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
findreturnsundefined: This happens either because there's no element indatawith anOfficeIDmatchingthis.OfficeID, or there's a type mismatch (e.g.,this.OfficeIDis a string butOfficeIDis defined as a number in your type).- Incorrect logic order: You're sorting the original
dataarray 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. - Unsafe
push: Iftopofficeisundefined, callingpushwill throw an error. - String-based date comparison: Comparing
DateSubmittedas strings works for ISO 8601 formats (likeYYYY-MM-DD), but it's unreliable for other date formats. Converting toDateobjects 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.OfficeIDis a number (matching theOfficeIDtype inIOfficeInfo). If it's coming from user input or a string source, convert it withNumber(this.OfficeID)first. - Double-check that your
dataarray actually contains an element with theOfficeIDvalue stored inthis.OfficeID(you can logthis.OfficeIDanddatato confirm).
内容的提问来源于stack exchange,提问作者John
相关产品推荐
相关产品推荐

