Reputation: 1859
I've looked through several posts with similar with issues but I couldn't find one which solves my problem. The others all seemed to be sorting using another array of the same size or by value.
I have two arrays which look like this:
var allCategories = ['Campus', 'Building', 'Floor', 'Room', 'Lecture Theatre', 'Lab'];
var currentCategories = ['Room', 'Lab', 'Campus'];
How can I sort currentCategories
so that the order matches that of allCategories
?
Desired output:
currentCategories --> ['Campus', 'Room', 'Lab'];
Upvotes: 0
Views: 917
Reputation: 1981
If all that you want is the order of allCategories
with the members of currentCategories
, you can do the following.
allCategories.filter(function(x){return currentCategories.indexOf(x) != -1})
This assumes that you are treating each array
as a set of non-repeating elements. As mentioned in the comments, this method may drop duplicate elements from the final value, or not order duplicate elements in the way you might intend.
Upvotes: 3
Reputation: 1669
The Array.Sort
method can be supplied a custom function. You could do something like this:
currentCategories.sort(function(a, b) {
var i = allCategories.indexOf(a),
j = allCategories.indexOf(b);
return i - j;
});
I haven't checked the behaviour for when there are values in currentCategories
that are not in allCategories
. But then, it wouldn't be living up to its name if that were the case.
If this is a common case, you could generalise it along the following lines:
function sortByList(list) {
return function (a, b) { return list.indexOf(a) - list.indexOf(b); };
}
And call it thusly:
currentCategories.sort(sortByList(allCategories));
Upvotes: 0
Reputation: 198334
"Sort this array by the indices of its elements in that array":
currentCategories.sort(function(a, b) {
return allCategories.indexOf(a) - allCategories.indexOf(b);
});
// => ["Campus", "Room", "Lab"]
Upvotes: 5