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);
Approach 2: Early Exit Priority Search
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
findIndexthree times plus aforEach) - 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
相关产品推荐
相关产品推荐

