JavaScript switch case: anyway to force the order

2019-08-29 00:10发布

问题:

I've got results being returned to a Google Mapping application in the div sidebar. The results are names of businesses that belong to categories that the client wants returned in a certain order. And unfortunately it's not a straight alpha sort. So one category begins with F and the second one with a C and the last three are A's, for example.

So I need my switch, which works, but naturally insists on dropping the values in alpha sorted (as they are returned from the DB that way) order as that's how it encounters them. What's the best way to set this up so I can grab my preferred categories with their associated company names in the arbitrary order the client has asked for?

Thanks!

回答1:

Can you iterate over the categories in the order you want them in, and find the object to which it is associated?

E.g. (pseudocode)

var categories = [ 'F', 'C', 'A1', 'A2', 'A3' ].map(function (category) {
    return businesses.filter(function (business) {
        return business.category === category;
    });
});


回答2:

So the missing step in the answer given here was HOW the map would be implemented and HOW the JS snippet could be implemented. Anyway, I ended up having to ask that as a separate question and finally got a nice working example for an answer.

Russ wrote:

The code given looks most likely to be using the jQuery JavaScript library that has some useful functions such as map() for manipulating arrays.

If we go back to the original problem, you need to order a list of categories based on the client's preference. Let's create a an object literal to map the ordering

var map = {
     F : 5,
     C : 3,
     A1 : 1,
     A2 : 4,
     A3 : 2
 }

We can use this map to order the array using the sort method

 var array = ['F', 'C', 'A1', 'A2', 'A3'];

 array.sort(function(a,b) {
     return map[a] - map[b];
 });
 This returns us ["A1", "A3", "C", "A2", "F"]

Anyway, I wanted to make sure this was included on this thread for anyone searching for this issue in the future or anyone following along right now. Thanks for everyone's input!