This just came up over at CADTutor, and I was pretty dissatisfied with my solution, so I thought I'd post it as a bit of an exercise..
The task is to sort a list using another list as a reference, hence:
(setq CorrectOrder '("D" "B" "C" "A"))
(setq Lst '("A" "B" "C" "D"))
(SortByList Lst CorrectOrder) ==>> ("D" "B" "C" "A")
This was the code that I hacked together:
(defun SortByList (lst ord)
(mapcar
(function
(lambda (x)
(nth x lst)))
(mapcar
(function
(lambda (x)
(vl-position x lst))) ord)))
Of course this errors out if there is an element in 'CorrectOrder' that doesn't appear in 'Lst'...
So I got around it by this:
(defun SortByList (lst ord)
(setq ord (vl-remove-if-not
(function
(lambda (x) (vl-position x lst))) ord))
(mapcar
(function
(lambda (x)
(nth x lst)))
(mapcar
(function
(lambda (x)
(vl-position x lst))) ord)))
And then there is the situation when there is an element in 'Lst' that is not in 'CorrectOrder', causing it to be omitted from the result...
So I got around it like this:
(defun SortByList (lst ord / new)
(setq ord (vl-remove-if-not
(function
(lambda (x) (vl-position x lst))) ord))
(setq new (mapcar
(function
(lambda (x)
(nth x lst)))
(mapcar
(function
(lambda (x)
(vl-position x lst))) ord)))
(append new (vl-remove-if
(function
(lambda (x) (vl-position x new))) lst)))
But as I say, less than ideal...
So I leave it open to suggestions!
Enjoy