Function Repository Resource:

SortLike

Source Notebook

Sort a list so that elements in common with another list are in the same order

Contributed by: Bob Sandheinrich

ResourceFunction["SortLike"][l1,l2]

sorts elements in the list l1in the same order as in l2.

ResourceFunction["SortLike"][l]

gives an operator that sorts lists like l.

Details

ResourceFunction["SortLike"][l2][l1] is equivalent to ResourceFunction["SortLike"][l1,l2].
Elements not included in l2 are included at the end of the result in the same order.

Examples

Basic Examples (3) 

Sort a list like another list:

In[1]:=
ResourceFunction["SortLike"][{1, 2}, {2, 1}]
Out[1]=

Sort names according to an existing list:

In[2]:=
ResourceFunction[
 "SortLike"][{"Bob", "Rick", "Sushma", "Danny", "Paco"}, {"Sushma", "Rick", "Danny"}]
Out[2]=

Create an operator:

In[3]:=
sorter = ResourceFunction["SortLike"][{"Apples", "Bananas", "Grapes"}]
Out[3]=

Sort some fruit:

In[4]:=
sorter[{"Watermelon", "Grapes", "Apples", "Blueberries"}]
Out[4]=

Scope (1) 

Sort integers based on an existing list:

In[5]:=
l = RandomInteger[10, 5]
Out[5]=
In[6]:=
ResourceFunction["SortLike"][Range[0, 10], l]
Out[6]=

Requirements

Wolfram Language 11.3 (March 2018) or above

Version History

  • 1.1.0 – 22 February 2023
  • 1.0.0 – 04 March 2019

Related Resources

Author Notes

Version 1.1.0: speed improvement suggested by Sjoerd Smit

License Information