Home > Back-end >  How to find index nested object within array in javascript
How to find index nested object within array in javascript

Time:12-07

I have an JS array with nested objects as a "task list". They each are added with different Urgency properties. Now my function needs to find the highest urgency value - set this to a variable and then remove it from the array. I am stuck at removing it from the original array. The trouble i have might just be finding the index:

function newTask() {

  // reducing the "task list" to just the highest urgency
  let maxObj = taskList.reduce((max, obj) => (max.stockUrgency > obj.stockUrgency) ? max : obj);
  
  outputNewtask = JSON.stringify(maxObj, null, 4); 
 
 let index = taskList.indexOf("outputNewtask")
 
 console.log(index)

CodePudding user response:

If your reduce works fine, then you can use that object to find the index and remove it from the list using splice:

    let maxObj = taskList.reduce((max, obj) => (max.stockUrgency > obj.stockUrgency) ? max : obj);

    taskList.splice(taskList.indexOf(maxObj), 1);

    outputNewtask = JSON.stringify(maxObj, null, 4); 

CodePudding user response:

This code should solve your problem

const highestUrgencyValue = Math.max(...taskList.map(t => t.stockUrgency));
const highestUrgencyIndex = taskList.findIndex(task => task.stockUrgency === highestUrgencyValue);
taskList.splice(highestUrgencyIndex, 1);
  • Related