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

如何优化JS数组搜索函数?并实现数组重排的同类方案

Optimizing the Minimum DisplayOrder Key Function & Sorting by DisplayOrder

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:

  • reduce iterates through every element in the array, comparing each item's displayOrder to the current minimum.
  • It returns the object with the smallest displayOrder, then we just grab its key property.
  • 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 displayOrder might 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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 12:13:59