Search code examples
javascriptarraysloopsecmascript-6

efficient way to return single element by priority order in array of objects javascript


I have following array with three elements:

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

Now I declare an empty array which should return an element based on the priority

let priorityTask = []; 

Now, the priority task should return { type: 'critical', value: 'production issue' } since critical type would have highest priority.

If critical type is not available in the array of tasks then it should return { type: 'high', value: 'server down' } as high type would have second priority and like wise.

I have written the following code to get the output which looks just fine But, if we have a large set of array of tasks ? how can we refactor the code to make it better.

Priority Order: Critical - High - Medium

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);

{
  type: 'critical',
  value: 'production issue'
}

Solution

  • const priority = ['critical', 'high', 'medium'];
    let priorityTask = priority.map(p => tasks.find(task => task.type === p)).find(task => task !== undefined);
    
    console.log('priorityTask:', priorityTask);
    

    Using the priority array we define a sort of hierarchy and find will return the first occurence, so your desired output.