All orderings of a list
A JavaScript exercise from Scriptdrill. Solve it with a code editor in your browser that runs your function against example and hidden tests, and it is checked the moment you submit.
The task
Return every ordering of `items` as an array of arrays. The items are all different. List the orderings in this order: first all that start with the first item, then all that start with the second item, and so on, with the same rule applied to the rest of each ordering. So `[1, 2, 3]` gives `[1,2,3]`, `[1,3,2]`, `[2,1,3]`, `[2,3,1]`, `[3,1,2]`, `[3,2,1]`. An empty array has exactly one ordering, the empty one, so the result is `[[]]`. Do not change `items`.
What this exercise teaches
Each call fixes one element and hands the rest to a smaller version of the same problem; the empty array is the base case and returns one empty ordering, so that there is something to build on. Going through the items by position, not by value, gives the required order without sorting.
A hint if you get stuck
Use recursion: for each position `i`, take `items[i]` as the first element and put it in front of every permutation of the remaining items. The permutations of an empty array are `[[]]`.
Try it now, free, no account needed
Every exercise on Scriptdrill is free to try. Open it on the practice page, solve it, and get instant feedback with a hint. The worked solution opens once you solve it or after two tries.
Open this exerciseMore exercises in Data shaping
- CSV text to objectsFree
- Totals per customerFree
- Pivot rows into a lookupFree
- Top N with tiesFree
- Running totalsFree
- Read a nested value by pathFree
- Deep equalityFree
- Flatten a nested objectFree
- Left join two listsFree
- Merge overlapping intervalsFree
- Most frequent valuesFree
- Deep cloneFree
- Unflatten dotted keysFree
- Flat list to a treeFree