We have an array that we will sort
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,
},
]
We also have a map in which the array needs to be sorted
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],
}
Result must be
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,
},
]
Sorting takes place in this order, we have companyId, this is the key to the array, in which there should be an array, for example companyId = 165, and the objects in the result array should go in this order [58, 468, 67], objects with some ids may be omitted
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])