Tengo una variedad de objetos como a continuación,
[ { id: 1, holiday_for: 1, holiday_on: "2021-10-26" }, { id: 2, holiday_for: 3, holiday_on: "2021-10-26" }, { id: 3, holiday_for: 1, holiday_on: "2021-11-26" }, { id: 4, holiday_for: 3, holiday_on: "2021-11-26" }, { id: 5, holiday_for: 4, holiday_on: "2021-11-26" } ]donde los objetos tienen las mismas fechas pero diferente holiday_for. holiday_for tiene 3 tipos 1, 3, 4. Estoy tratando de encontrar un objeto con las mismas fechas que tenga max holiday_for.
Si la matriz tiene 2 objetos con las mismas fechas y tipos 1 y 3, 3 tendrán prioridad alta. Si tiene 3 objetos con las mismas fechas con los tipos 1, 3, 4, entonces 4 tendrán prioridad.
Intenté usar reduce pero solo devuelve el objeto con el tipo más alto:
const filtered = holidays.reduce((max, cur) => max.holiday_for > cur.holiday_for ? max : cur )Tipo de salida
[ { id: 2, holiday_for: 3, holiday_on: "2021-10-26" }, { id: 5, holiday_for: 4, holiday_on: "2021-11-26" } ] holidays_sorted = holidays.sort((a,b)=>{ if(a.holiday_on === b.holiday_on){ return b.holiday_for - a.holiday_for } }) let unique = {}; holidays_sorted = holidays.filter(holiday=> { if (unique[holiday.holiday_on]) { return false; } unique[holiday.holiday_on] = true; return true; }); //keep first unique holiday_on for each date Which is the higher {id: 2, holiday_for: 3, holiday_on: '2021-10-26'}//<--this {id: 1, holiday_for: 1, holiday_on: '2021-10-26'} {id: 5, holiday_for: 4, holiday_on: '2021-11-26'}//<--that {id: 4, holiday_for: 3, holiday_on: '2021-11-26'} {id: 3, holiday_for: 1, holiday_on: '2021-11-26'}Resultado:
{id: 2, holiday_for: 3, holiday_on: '2021-10-26'} {id: 5, holiday_for: 4, holiday_on: '2021-11-26'}Como estoy usando Angular, necesito agregar algunos tipos. Basado en la respuesta de @Mehdi Taher , agregué algo de escritura y terminé así:
const sortedHolidays = holidays.sort( (a: IHoliday, b: IHoliday) => { return a.holiday_on === b.holiday_on ? b.holiday_for - a.holiday_for : 0; } ); let unique: { [key: string]: IHoliday | boolean } = {}; const filtered = duplicateHolidays.filter( (holiday: IHoliday) => { if (unique[holiday.holiday_on]) { return false; } unique[holiday.holiday_on] = true; return true; } );Si entiendo correctamente, algo como lo siguiente.
let ordered = array .filter(a => a.holiday_on == "2021-11-26") .sort((a, b) => b.holiday_for - a.holiday_for); let priority = ordered[0].holiday_for; ordered.filter(a => a.holiday_for == priority);