Tenemos una matriz que ordenaremos
nonSortArray = [ { typeId: 67, id: 13296, companyId: 165, }, { typeId: 67, id: 13446, companyId: 165, }, { typeId: 118, id: 10996, companyId: 84941, }, { typeId: 58, id: 13796, companyId: 165, }, { typeId: 58, id: 12596, companyId: 165, }, { typeId: 7, id: 137962, companyId: 10134, }, { typeId: 10, id: 125961, companyId: 10134, }, { typeId: 16, id: 13296, companyId: 112290, }, { typeId: 67, id: 132976, companyId: 105951, }, { typeId: 10, id: 122596, companyId: 112290, }, ]También tenemos un mapa en el que la matriz debe ordenarse
map = { 165: [58, 468, 67], 211: [10, 4, 33, 3, 768, 9, 1218, 15], 5388: [33, 3], 10134: [36, 10, 5, 6, 7, 1718, 33, 3, 31], 31516: [22, 7], 84941: [118], 90791: [16, 31], 105951: [67], 112290: [10, 33, 3, 1919, 16, 1918], 114767: [5], 144872: [2569, 2570, 1118], }El resultado debe ser
result = [ { typeId: 58, id: 13796, companyId: 165, }, { typeId: 58, id: 12596, companyId: 165, }, { typeId: 118, id: 10996, companyId: 84941, }, { typeId: 67, id: 13296, companyId: 165, }, { typeId: 67, id: 13446, companyId: 165, }, { typeId: 10, id: 125961, companyId: 10134, }, { typeId: 7, id: 137962, companyId: 10134, }, { typeId: 10, id: 122596, companyId: 112290, }, { typeId: 67, id: 132976, companyId: 105951, }, { typeId: 16, id: 13296, companyId: 112290, }, ]La clasificación se lleva a cabo en este orden, tenemos companyId, esta es la clave de la matriz, en la que debe haber una matriz, por ejemplo companyId = 165, y los objetos en la matriz de resultados deben ir en este orden [58, 468, 67], los objetos con algunos identificadores pueden omitirse
const result = Object.entries(map).reduce((acc, el) => { const [companyId, types] = el; if (acc.find(s => s.companyId === +companyId)) { const sortingByTypes = types.map(l => { if (acc.some(m => m.typeId === l)) { return acc.filter(m => m.typeId === l) } return null; }) const getArraySortingByTypes = sortingByTypes.reduce((curAcc, x) => { if (x) { curAcc.push(...x) } return curAcc }, []) // Stuck in this for replace object for right position } return acc; }, [...nonSortArray])