Jaydo
Jaydo

Reputation: 1859

Sort an array based on values from another array of different length

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

Answers (3)

isomarcte
isomarcte

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

md4
md4

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

Amadan
Amadan

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

Related Questions