Wolfram Research

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 and Options

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

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

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

Resource History

License Information