Skip to content Skip to sidebar Skip to footer

Javascript Switch Case: Anyway To Force The Order Of The Elements As They Are Written Out?

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

Solution 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;
    });
});

Solution 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

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

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

vararray = ['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!

Post a Comment for "Javascript Switch Case: Anyway To Force The Order Of The Elements As They Are Written Out?"