Let's say we have the following array:
const array = [
{ name: 'b' },
{ name: 'a' },
{ name: 'c' },
]
The objective is to add a new property to each object based on its position in the sorted array:
const array = [
{ name: 'b', sortIndex: 1 },
{ name: 'a', sortIndex: 0 },
{ name: 'c', sortIndex: 2 },
]
One approach is to first sort the array by name, then iterate through and assign index values as follows:
const array = [
{ name: 'a', sortIndex: 0 },
{ name: 'b', sortIndex: 1 },
{ name: 'c', sortIndex: 2 },
]
However, the current solution involves multiple loops which may not be efficient. Any suggestions on how to improve this process?
export function setSortIndexes(series) {
const clone = cloneDeep(series);
const sorted = orderBy(clone, [
(x) => (x.name ? x.name.toLowerCase() : null),
]);
sorted.forEach((x, i) => {
x.sortIndex = i;
});
series.forEach(x => {
const index = sorted.findIndex((s) => s.name === x.name);
if (index !== -1) {
x.sortIndex = sorted[index].sortIndex;
}
});
return series;
}