Created
October 16, 2016 04:03
-
-
Save jasonwaters/c2bab39280693213f29af94085cb43e5 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| //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] |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
actually, this is a much better way to do it....