I have an array (let’s call it the orderArray) with these elements:
16 | 18 | 24 | 31 | 33
I have another array (let’s call it workingArray) with these elements:
16 | 53 | 24 | 58 | 31 | 18
The resultArray could be as follows:
[16, 53, 18, 24, 58, 31], or [16, 18, 53, 24, 58, 31] for example
resultArray should have all the elements from workingArray but with a sorting order that doesn’t conflict with orderArray.
Please note
- orderArray and workingArray can have different elements between each other
- elements are unique within the array
I would be really happy if there is already a function/library that does that – I have already tried _.union but that doesn’t do the job.
Short of some already-made code, what’s the easiest algorithm to achieve that?
Thanks.
EDIT: the sort order of the elements in resultArray should be changed as less as possible – changes should be strictly done not to conflict with the order in orderArray.
main idea:
(copy
orderArrayignoring items not in the working array, then tack on items in theworkingArraythat weren’t in the order array)you can use
indexOfto test membership, or a more efficient implementation (making all the elements keys in an object, which will implicitly convert them to strings, making that optimization not work with non-primitive objects). Below is the simplest example with justindexOf, which should generalize even to non-primitive objects like sub-arrays:result:
The question is still not well defined, but this will sort the subset of the workingArray according to the orderArray, leaving elements not in the orderArray in place:
result: