One side-effect of using sort
on the newIndexOfPerson is that it performs sorting in place, rather than returning a new array with the entries sorted, so newIndexOfPerson array itself will be modified.
If this is unwanted, you may sort a copy of this array (use newIndexOfPerson.slice()
to make one).
However, if you really need 2 arrays to read data from and you know the correct indecies to begin with, rather than trying sort
with a custom sorter, it may be more elegant and faster to use reduce
to create a new array and fill its entries according to the indecies and data specified in newIndexOfPerson:
arrayOfPersons = newIndexOfPerson.reduce((newArrayOfPersons, entry) => {
newArrayOfPersons[entry.newPersonIndex] = {
myName: entry.myName
};
return newArrayOfPersons;
},
new Array(arrayOfPersons.length)
);
This code has linear time complexity, while sort
has logarithmic complexity.
It can be easily modified work with "old indecies" in newIndexOfPerson instead of just plain data. This solution, of course, expects that the lengths of arrays match and all the indecies are set correctly (otherwise, you'll get gaps in the resulting array).