I have the following arrangements on a mechanical workshop. In which I want to order the cars with their respective mechanics.
let mecanicos = [
{ id: 1, rut: '132254524', name: 'Pepe'},
{ id: 2, rut: '143618668', name: 'Carlos'},
{ id: 6, Rut: '78684747', name: 'Ricardo' }
];
let autos = [
{ id: 1, name: 'nissan versa' },
{ id: 2, name: 'toyota corola' },
{ id: 3, name: 'chevrolet aveo' }
];
let reparaciones = [
{ idMecanico: 1, idauto: '3', falla: 'motor'},
{ idMecanico: 2, idauto: '1', falla: 'escape'},
{ idMecanico: 2, idauto: '2', falla: 'radiador'},
{ idMecanico: 3, idauto: '1', falla: 'radiador'},
{ idMecanico: 3, idauto: '3', falla: 'radiador'},
{ idMecanico: 3, idauto: '2', falla: 'escape'},
{ idMecanico: 3, idauto: '2', falla: 'llanta'}
];
function AutosPorMecanico() {
let names = mecanicos.map((mecanico) => mecanico.name);
const objeto = {};
names.forEach(function (a) {
objeto [a] = [autos.map((auto) => auto.name).sort()];
});
return objeto;
}
console.log(AutosPorMecanico());
I am creating the object with a foreach but clearly I am only assigning the three cars to each name when each name should only show the ones that are actually assigned... Thank you very much in advance!
If I understood correctly this is what you want, otherwise let me know so I can change the code.
I think the maps that you had do not apply, for this case a reduce is better, where we verify if the mechanic has a repeated car, then a function to return the car according to its ID (GetAuto)
Try this snippet. The code is similar to the previous one but the result is sorted by mechanic name and also by car name.