finding the highest value for an attribute in a database

27 Views Asked by At

I have a database with Canadian province and cumulative data entry for a disease notification. I would like to use my highest disease reporting for each province. Province Number of cases Cumulative number Quebec 1 1 Ontario 2 2 Quebec 1 2 Quebec 1 3 BC 4 4 BC 1 5 etc

This is the data I would like to get Quebec 3 Ontario 2 BC 5

Can anyone tell me how to code this in javascript. My data base is in Json. Please note that I have minimum coding experience THank you

Not sure if

  1. first only add all data from the first column and use result
  2. select highest value for each province from cumulative data
  3. select last data entry for each province
1

There are 1 best solutions below

0
MalwareMoon On

Assuming that data are arrays of arrays as no keys were mentioned:

const data = [
  ["Quebec", 5],
  ["Quebec", 1],
  ["Quebec", 5],
  ["Ontario", 1],
  ["Ontario", 2],
  ["Ontario", 1]
];

function compare(a, b) {
  if (a[1] > b[1]) {
    return -1;
  }
  if (a[1] < b[1]) {
    return 1;
  }
  return 0;
}

const firstHighest = [];
// This variable is here both because I was lazy and it will run faster
const inserted = [] 

data.sort(compare).forEach((item) => {
  if(!inserted.includes(item[0])){
    firstHighest.push(item)
    inserted.push(item[0])
  }
})

console.log(firstHighest)

Unless you give exact specifications this is probably the most I can do. Glad to help with your homework.