Looking to implement a custom sorting method for an array that consistently arrives in varying orders:
[{code: 'A'},{code: 'O'},{code: 'I'}], [{code: 'O'},{code: 'A'},{code: 'I'}], ...
The desired order is
[{code: 'A'},{code: 'O'},{code: 'I'}]
.
export function customSort(arrayToSort): Array {
if (!arrayToSort || arrayToSort.length < 1) {
return [];
}
const sorted = new Map();
const sorting = ['A', 'O', 'I'];
for (let i = 0; i < sorting.length; ++i) {
sorted.set(sorting[i], i);
}
return arrayToSort.sort((a, b) => sorted.get(a.code) - sorted.get(b.code));
}
An attempt was made by creating a map with the desired sorting configuration, setting keys as 'A' and values as numbers to facilitate sorting. However, an error occurred:
core.js:15724 ERROR TypeError: Cannot assign to read only property '0' of object '[object Array]'
. At this point, further solutions are needed.