Skip to content

Instantly share code, notes, and snippets.

@jasonwaters
Created October 16, 2016 04:03
Show Gist options
  • Select an option

  • Save jasonwaters/c2bab39280693213f29af94085cb43e5 to your computer and use it in GitHub Desktop.

Select an option

Save jasonwaters/c2bab39280693213f29af94085cb43e5 to your computer and use it in GitHub Desktop.
//we have an array of objects A and an array of indexes B. Reorder objects
//in array A with given indexes in array B. Do not change array A's length;
var A = ['C', 'D', 'E', 'F', 'G'];
var B = [3, 0, 4, 1, 2];
function resort(arr, order) {
let idx=0;
for(var start=0;start<arr.length;start++) {
for(var i=start;i<arr.length;i++) {
if(B[i] == idx) {
let value = arr.splice(i, 1);
arr.splice(idx, 0, value[0]);
value = order.splice(i, 1);
order.splice(idx, 0, value[0]);
idx++;
break;
}
}
}
}
resort(A, B);
console.log(A); // [D, F, G, C, E]
console.log(B); // [0, 1, 2, 3, 4]
@jasonwaters

jasonwaters commented Jan 11, 2017

Copy link
Copy Markdown
Author

actually, this is a much better way to do it....

let A = ['C','D','E','F','G'];
let B = [  3,  0,  4,  1,  2];

sort(A, B);

console.log(A); //D, F, G, C, E

function sort(values, sequence) {
  let indexed = [];
  
  sequence.forEach((value, idx) => indexed[value] = values[idx]);
  indexed.forEach((value, idx) => values[idx] = value);
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment