Group Array by matches

0

My question goes first because I am developing a project where I need to list the medications associated with a medical formula, but after saving the data when I visualize them, I repeat the heading of the formula multiple times, for which I need to make a grouping of medicines that have a id_formula in common. This is the Array that comes from the database:

let array = [
    {"id_formula":"12342341234123","fecha_formula":"2018-10-18 00:00:00","id_residente":42999857,"dosis_medicamento":2,"lapso":6,"dias":8,"nombre_medicamento":"Acetaminofen","dosis":100,"unidad_medida":"mg","nombre_aplicacion":"Sublingal"},
    {"id_formula":"12342341234123","fecha_formula":"2018-10-18 00:00:00","id_residente":42999857,"dosis_medicamento":1,"lapso":12,"dias":10,"nombre_medicamento":"Naproxeno","dosis":500,"unidad_medida":"mg","nombre_aplicacion":"Oral"},
    {"id_formula":"1234567890987","fecha_formula":"2018-10-18 00:00:00","id_residente":12345678,"dosis_medicamento":1,"lapso":5,"dias":2,"nombre_medicamento":"Clonacepan","dosis":25,"unidad_medida":"mg","nombre_aplicacion":"Oral"},
    {"id_formula":"1234567890987","fecha_formula":"2018-10-18 00:00:00","id_residente":12345678,"dosis_medicamento":3,"lapso":12,"dias":3,"nombre_medicamento":"Acetaminofen","dosis":100,"unidad_medida":"mg","nombre_aplicacion":"Sublingal"}]

And I need something of the kind:

let array = [
    {"id_formula":"12342341234123",
     "fecha_formula":"2018-10-18 00:00:00",
     "id_residente":42999857,
     "medicamentos": [
         {"dosis_medicamento":2,
          "lapso":6,
          "dias":8,
          "nombre_medicamento": "Acetaminofem",
          "dosis": 100,
          "unidad_medida": "mg",
          "nombre_aplicacion": "Sublingual"
         },
         {"dosis_medicamento":1,
          "lapso":12,
          "dias":10,
          "nombre_medicamento": "Naproxeno",
          "dosis": 500,
          "unidad_medida": "mg",
          "nombre_aplicacion": "Oral"
         }
       ]
     },
     {"id_formula":"1234567890987",
     "fecha_formula":"2018-10-18 00:00:00",
     "id_residente":12345678,
     "medicamentos": [
         {"dosis_medicamento":1,
          "lapso":5,
          "dias":2,
          "nombre_medicamento": "Clonacepan",
          "dosis": 25,
          "unidad_medida": "mg",
          "nombre_aplicacion": "Oral"
         },
         {"dosis_medicamento":3,
          "lapso":12,
          "dias":3,
          "nombre_medicamento": "Acetaminofen",
          "dosis": 100,
          "unidad_medida": "mg",
          "nombre_aplicacion": "Sublingual"
         }
      ]
   }
]

I have been looking for a solution for 1 week and the only thing I find is to group only one of the medications, I would appreciate the help and it would be a great learning tool

Note: The data is fictitious

    
asked by David Acevedo 23.10.2018 в 07:39
source

2 answers

0

To do this you have to develop the grouping function yourself, one way to do it would be as follows:

  • Definition of the classes for the different objects:

Medication class

class Medicamento {
  dosis_medicamento: number;
  lapso: number;
  dias: number;
  nombre_medicamento: string;
  dosis: number;
  unidad_medida: string;
  nombre_aplicacion: string;
  constructor(
    dosis_medicamento,
    lapso,
    dias,
    nombre_medicamento,
    dosis,
    unidad_medida,
    nombre_aplicacion
  ) {
    this.dosis_medicamento = dosis_medicamento;
    this.lapso = lapso;
    this.dias = dias;
    this.nombre_medicamento = nombre_medicamento
    this.dosis = dosis;
    this.unidad_medida = unidad_medida;
    this.nombre_aplicacion = nombre_aplicacion;
  }
}

Formula class

class Formula {
    id_formula: string; 
      fecha_formula: string;
      id_residente:number; 
      medicamentos: Medicamento[] = [];

    constructor(
      id_formula, 
      fecha_formula, 
      id_residente){
        this.id_formula = id_formula;
        this.fecha_formula = fecha_formula;
        this.id_residente = id_residente;
    }

    addMedicamento(medicamento) {
        this.medicamentos.push(medicamento);
    }
}
  • Afterwards, you should have a function that iterates and makes the grouping of medicines by formula:

    function groupMedicamentosByFormula() {
       let array = [
       { "id_formula": "12342341234123", "fecha_formula": "2018-10-18 00:00:00", 
       "id_residente": 42999857, "dosis_medicamento": 2, "lapso": 6, 
       "dias": 8, "nombre_medicamento": "Acetaminofen", "dosis": 100, 
       "unidad_medida": "mg", "nombre_aplicacion": "Sublingal" },
       { "id_formula": "12342341234123", "fecha_formula": "2018-10-18 00:00:00", 
       "id_residente": 42999857, "dosis_medicamento": 1, "lapso": 12, 
       "dias": 10, "nombre_medicamento": "Naproxeno", "dosis": 500, 
       "unidad_medida": "mg", "nombre_aplicacion": "Oral" },
       { "id_formula": "1234567890987", "fecha_formula": "2018-10-18 00:00:00", 
       "id_residente": 12345678, "dosis_medicamento": 1, "lapso": 5, 
       "dias": 2, "nombre_medicamento": "Clonacepan", "dosis": 25, 
       "unidad_medida": "mg", "nombre_aplicacion": "Oral" },
       { "id_formula": "1234567890987", "fecha_formula": "2018-10-18 00:00:00", 
       "id_residente": 12345678, "dosis_medicamento": 3, "lapso": 12, 
       "dias": 3, "nombre_medicamento": "Acetaminofen", "dosis": 100, 
       "unidad_medida": "mg", "nombre_aplicacion": "Sublingal" }];
    
        var formulas: Formula[] = [];
        var auxFormula: Formula;
        var auxFormulas: Formula[];
    
        // recorremos el array
        array.forEach((item) => {
           // obtenemos la formula si ya esta en el array de formulas
           auxFormulas = formulas.filter((formula) => formula.id_formula === item.id_formula);
    
          auxFormula = auxFormulas.length === 0 ? undefined : auxFormulas[0];
          // si no existe creamos la formula y la añadimos al array
          if (!auxFormula) {
            auxFormula = new Formula(item.id_formula, item.fecha_formula, item.id_residente);
            formulas.push(auxFormula);
          }
    
          // si ya existe el medicamento dentro de la formula pasamos al siguiente medicamento
          if (auxFormula.medicamentos.filter((medicamento) => medicamento.nombre_medicamento === item.nombre_medicamento).length > 0) {
            return;
          }
    
          // si no existe el medicamento lo añadimos en la formula
          auxFormula.addMedicamento(new Medicamento(item.dosis_medicamento, item.lapso, item.dias, item.nombre_medicamento, item.dosis, item.unidad_medida, item.nombre_aplicacion));
        });
    
        console.log(auxFormula);
    
      }
    
answered by 23.10.2018 / 08:35
source
0

Possible solution:

class Test {

    constructor() {
        this.filterFormulas();
    }

    private filterFormulas() {
        console.log('filterFormulas()'); // HACK: trace

        const arr = [
            {
                'id_formula': '12342341234123',
                'fecha_formula': '2018-10-18 00:00:00',
                'id_residente': 42999857,
                'dosis_medicamento': 2,
                'lapso': 6,
                'dias': 8,
                'nombre_medicamento': 'Acetaminofen',
                'dosis': 100,
                'unidad_medida': 'mg',
                'nombre_aplicacion': 'Sublingal'
            },
            {
                'id_formula': '12342341234123',
                'fecha_formula': '2018-10-18 00:00:00',
                'id_residente': 42999857,
                'dosis_medicamento': 1,
                'lapso': 12,
                'dias': 10,
                'nombre_medicamento': 'Naproxeno',
                'dosis': 500,
                'unidad_medida': 'mg',
                'nombre_aplicacion': 'Oral'
            },
            {
                'id_formula': '1234567890987',
                'fecha_formula': '2018-10-18 00:00:00',
                'id_residente': 12345678,
                'dosis_medicamento': 1,
                'lapso': 5,
                'dias': 2,
                'nombre_medicamento': 'Clonacepan',
                'dosis': 25, 'unidad_medida': 'mg',
                'nombre_aplicacion': 'Oral'
            },
            {
                'id_formula': '1234567890987',
                'fecha_formula': '2018-10-18 00:00:00',
                'id_residente': 12345678,
                'dosis_medicamento': 3,
                'lapso': 12, 'dias': 3,
                'nombre_medicamento': 'Acetaminofen',
                'dosis': 100, 'unidad_medida': 'mg',
                'nombre_aplicacion': 'Sublingal'
            }
        ];

        const response = this.filterByFormulaId(arr);
        console.log('Filtered formulas:'); // HACK: trace of results
        console.log(response);
    }

    private filterByFormulaId(arr: any): any {
        console.log('filterByFormulaId()'); // HACK: trace

        const response = [];
        const arrLength = arr.length;
        console.log('Elements to filter: ' + arrLength); // HACK: trace

        for (let i = 0; i < arrLength; i ++) {
            const formula = arr[i];
            // console.log('Show formula ' + i);  // HACK: traces
            // console.log(formula);

            if (! this.isInArrayOfFormulas(formula, response)) {
                response.push(formula);
            }
        }

        return response;
    }

    private isInArrayOfFormulas(formula: any, response: any): boolean {
        console.log('isInArrayOfFormulas()'); // HACK: trace

        const arrLength = response.length;
        for (let i = 0; i < arrLength; i++) {
            console.log('To analize - ID: ' + formula.id_formula); // HACK: trace

            // Check each element by 'id_formula'
            if (response[i].id_formula === formula.id_formula) {
                return true;
            }
        }

        return false;
    }
}

new Test();

Result:

Explanation

Each element of the array is traversed, that is, each formula, to be compared if the property id_formula is repeated, for this we use isInArrayOfFormulas() that returns a boolean according to whether it finds that id or not, receiving the current formula (of each iteration) and an array where the formulas are saved (excluding the repetitions, according to 'id_formula').

I have left some traces, you can see that although four elements are analyzed, only one ID is being compared three times, that is because the first element of the original array enters directly into the resulting array, that is, it is not going to iterate array resulting in isInArrayOfFormulas() when it is empty.

Note

I have stuck to solving your problem, filter the elements so that they do not repeat according to the property 'id_formula' . I no longer know if your data or logic to obtain them is correct. I noticed that in two elements with the same 'id_formula' there are data that differ, such as the dose or the name of medication, when doing the filtering you will only have the data the data of the first element, you will lose the rest of the elements with the id repeated.

Greetings.

    
answered by 23.10.2018 в 08:48