Godshand
Godshand

Reputation: 631

How to find the max value inside a multiple key array?

I have here my router to get the values from my mongodb while checking its total sum:

router.get('/bloodinventory', function(req, res) {
      Bloodinventory.aggregate([{$group: {_id : "$blood_category" , count :{$sum:"$num_stock"}}},{$sort: {_id: 1}}],function(err, inventory) {     
      res.json({ success: true, inventory: inventory });
    });  
});

Then in my controller i have this function to initialize it to my charts:

function getChart() {

    Bloodinventory.getChart().then(function(data) {
        console.log(1, data.data.inventory);
        app.inventory = data.data.inventory; 
        initChart();      
    });
}

Here is the sample output of my console:

[{_id: "aspheresis platelets", count: 264} 
 {_id: "cryoprecipitate",count: 330}]

My question is, how can I get the max value of count inside the inventory array?

Upvotes: 0

Views: 33

Answers (2)

Code Maniac
Code Maniac

Reputation: 37755

Use a for loop keep track of max value in a variable.

let obj = [{_id: "aspheresis platelets", count: 264},{_id: "cryoprecipitate",count: 330}]

let max = -Infinity

for( let i=0; i< obj.length; i++){
  if(obj[i].count > max) {
    max = obj[i].count; 
  } 
}
console.log(max)

Sort it in descending order. and than access count of 0th index element.

let obj = [{_id: "aspheresis platelets", count: 264},{_id: "cryoprecipitate",count: 330}]
 
let op = obj.sort((a,b)=> b.count-a.count)[0].count
 
console.log(op)

Upvotes: 1

mhodges
mhodges

Reputation: 11116

You can do this by using the .reduce() function of an array very easily, like so:

The idea is to keep track of the object with the highest count and compare it to each of the items in the list. The reduce function will return the item with the largest count when it has gone through the entire list. Similarly, in the second example below, you can just grab the number by using Math.max() to compare all of the counts.

var data = [
  {_id: "item1", count: 300},
  {_id: "item2", count: 265},
  {_id: "item3", count: 410},
  {_id: "item4", count: 115},
  {_id: "item5", count: 395},
];

var highestCountObject = data.reduce((res, item) => item.count > res.count ? item : res, {count: -Infinity});

console.log(highestCountObject);

var highestNumber = Math.max(...data.map(item => item.count));

console.log(highestNumber);

Upvotes: 1

Related Questions