Home > Net >  How to get sum of tickets as per priority from an array using javascript
How to get sum of tickets as per priority from an array using javascript

Time:09-29

I have the following array

{
agent_id:001,
priority:"High",
task_id:T1
},
{
agent_id:001,
priority:"High",
task_id:T1
},
{
agent_id:001,
priority:"Medium",
task_id:T1
}
{
agent_id:002,
priority:"High",
task_id:T1
}

I need to get an output of the above array as follows:

{agent_id:001,High_Count:2,Medium_Count:1},
{agent_id:002,High_Count:1,Medium_Count:0}

Here is my code:

for (let i = 0; i < dataModel.ticketList.length; i ) { var priority = JSON.stringify(dataModel.ticketList[i].Priority);

        if (!map.has(priority)) 
        {
         map.set(priority, {
            Agent: dataModel.ticketList[i].Agent,
            Low: 1,
         });
        } 
        else 
        {
         map.get(priority).Low  ;
        }
    }

const res = Array.from(map.values()) return res;

CodePudding user response:

You could use Array.prototype.reduce like this:

const data = [
  { agent_id: 001, priority: "High", task_id: "T1" },
  { agent_id: 001, priority: "High", task_id: "T1" },
  { agent_id: 001, priority: "Medium", task_id: "T1" },
  { agent_id: 002, priority: "High", task_id: "T1" },
];

const result = data.reduce((acc, cur) => {
  const index = acc.findIndex((x) => x.agent_id === cur.agent_id);

  if (~index) {
    const value = acc[index][`${cur.priority}_Count`] || 0;
    acc.splice(index, 1, {
      ...acc[index],
      [`${cur.priority}_Count`]: value   1,
    });
  } else {
    acc.push({ agent_id: cur.agent_id, [`${cur.priority}_Count`]: 1 });
  }

  return acc;
}, []);

console.log(result);

CodePudding user response:

Please use Array.reduce() function.

const data = [{ agent_id:001, priority:"High", task_id:"T1" }, { agent_id:001, priority:"High", task_id:"T1" }, { agent_id:001, priority:"Medium", task_id:"T1" }, { agent_id:002, priority:"High", task_id:"T1" }];

const urgent = "Urgent";

let result = data.reduce((total, item) => {
    if(total.map(val => val.agent_id).includes(item.agent_id)) {
        const index = total.map(val => val.agent_id).indexOf(item.agent_id);
        if(total[index].hasOwnProperty(item.priority   "_Count"))
            total[index][item.priority   "_Count"]   ;
        else
            total[index][item.priority   "_Count"] = 1;
    } else {
        let obj = {agent_id: item.agent_id};
        let priorities = data.map(val => val.priority).filter((val, i, self) => self.indexOf(val) === i);
        if(!!urgent) priorities.push(urgent);
        priorities.forEach(val => {obj[val   "_Count"] = 0});
        obj[item.priority   "_Count"] = 1;
        total.push(obj);
    }
    return total;
},[]);

result = result.map(val => {
    const total = Object.keys(val).reduce((total, key) => key === 'agent_id' ? total : total   val[key], 0);
    return {...val, total: total};
});

console.log(result);

  • Related