Skip to content

Instantly share code, notes, and snippets.

@gkucmierz
Created December 17, 2019 14:40
Show Gist options
  • Save gkucmierz/cbfd265a699b3f36c609453289363f49 to your computer and use it in GitHub Desktop.
Save gkucmierz/cbfd265a699b3f36c609453289363f49 to your computer and use it in GitHub Desktop.
// sort first array using another array
// - both arrays are same length
// - sort is stable
function sortUsing(a1, a2) {
const a = [];
for (let i = 0; i < a1.length; ++i) {
a[i] = [a1[i], a2[i], i];
}
return a.sort((a, b) => {
const d = a[1]-b[1];
return d === 0 ? a[2]-b[2] : d;
}).map(a => a[0]);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment