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

JavaScript中按优先级从对象数组返回单个元素的高效实现

Task Priority Selection Refactor

Problem Statement

Given the following task array:

const tasks = [
  { type: 'critical', value: 'production issue' },
  { type: 'high', value: 'server down' },
  { type: 'medium', value: 'backup not taken' }
];

We need to declare a variable priorityTask that stores the highest priority task, following the order: critical > high > medium. If a higher priority task exists, return it immediately; otherwise, fall back to the next level.

The current implementation is inefficient for large arrays, as it scans the array multiple times and uses unnecessary loops:

const criticalIndex = tasks.findIndex((task) => task.type === 'critical');
const highIndex = tasks.findIndex((task) => task.type === 'high');
const mediumIndex = tasks.findIndex((task) => task.type === 'medium');

tasks.forEach((task) => {
  if (criticalIndex >= 0) {
    task.type === 'critical' ? priorityTask = task : [];
  } else {
    if (highIndex >= 0) {
      task.type === 'high' ? priorityTask = task : [];
    } else {
      if (mediumIndex >= 0) {
        task.type === 'medium' ? priorityTask = task : [];
      }
    }
  }
});

console.log('priorityTask: ', priorityTask);

Optimized Solutions

Approach 1: Single Pass with Priority Mapping

Scan the array once and track the highest priority task found using a priority weight map:

// Define priority weights: higher value = higher priority
const priorityWeights = { critical: 3, high: 2, medium: 1 };
let priorityTask = null;

for (const task of tasks) {
  const currentWeight = priorityWeights[task.type];
  // Update priorityTask if current task has higher priority than stored one
  if (!priorityTask || currentWeight > priorityWeights[priorityTask.type]) {
    priorityTask = task;
  }
}

console.log('priorityTask: ', priorityTask);

Iterate through priority levels in order and stop at the first matching task (most efficient for large arrays):

const priorityOrder = ['critical', 'high', 'medium'];
let priorityTask = null;

for (const type of priorityOrder) {
  priorityTask = tasks.find(task => task.type === type);
  if (priorityTask) break; // Exit loop immediately when highest priority task is found
}

console.log('priorityTask: ', priorityTask);

Key Improvements

  • Reduced array scans: Both approaches avoid multiple full array iterations (original code uses findIndex three times plus a forEach)
  • Early termination: Approach 2 stops searching as soon as it finds the highest priority task, saving time on large datasets
  • Readability: Clear priority definition makes the code easier to maintain and modify

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.26 04:20:13