如何优化JS数组搜索函数?并实现数组重排的同类方案
Hey there! Let's break down your questions with clear, clean solutions that fix the original function's flaws and follow modern JavaScript best practices.
First: Fix & Optimize the Function to Find the Smallest displayOrder Key
Your original code has a critical issue—it returns on the first iteration of the for...in loop, so it never actually checks all elements to find the true minimum displayOrder. It only checks if the first item's value is 0, otherwise falls back to the first item's key. That won't work if there's an element with a smaller value (like a negative number) later in the array.
Here's a much cleaner, correct implementation using Array.reduce()—this is the most concise way to find the element with the minimum value in an array:
export const getMinDisplayOrderKey = () => { const data = [ { displayOrder: 0, key: 'key-name-1' }, { displayOrder: 2, key: 'key-name-2' }, // Add more items here if needed ]; // Handle edge case: empty array if (data.length === 0) return null; // Or your preferred fallback value // Reduce to find the object with the smallest displayOrder const minItem = data.reduce((currentMin, nextItem) => nextItem.displayOrder < currentMin.displayOrder ? nextItem : currentMin ); return minItem.key; };
Why this works:
reduceiterates through every element in the array, comparing each item'sdisplayOrderto the current minimum.- It returns the object with the smallest
displayOrder, then we just grab itskeyproperty. - Added an edge case check for empty arrays to avoid runtime errors.
Second: Sort the Entire Array by displayOrder
To sort the array by displayOrder (ascending by default), use Array.sort()—but remember, sort mutates the original array, so we'll create a copy first to preserve the original data (a best practice):
export const sortByDisplayOrder = (arr) => { // Create a shallow copy of the array to avoid mutating the original return [...arr].sort((a, b) => a.displayOrder - b.displayOrder); }; // Usage example with your data: const data = [ { displayOrder: 2, key: 'key-name-2' }, { displayOrder: 0, key: 'key-name-1' }, ]; const sortedData = sortByDisplayOrder(data); // sortedData will be: [{ displayOrder: 0, key: 'key-name-1' }, { displayOrder: 2, key: 'key-name-2' }]
Customization tips:
- For descending order (largest to smallest), reverse the comparison:
b.displayOrder - a.displayOrder - If
displayOrdermight be stored as a string (e.g., from an API response), convert it to a number first:Number(a.displayOrder) - Number(b.displayOrder)
内容的提问来源于stack exchange,提问作者Rob Fyffe

