vendredi 18 décembre 2015

Best way to order an array of strings in a defined order in Javascript?

I have an array of strings that I want to order using the string itself and a pre-defined order I have.

So the array could be:

['text4', 'image2', 'text1', 'text3', 'image1']

And the pre-defined order is this:

text1, image1, text2, image2, text3, image3, text4, image4, text5, image5

So the ordered array should look like this:

['text1', 'image1', 'image2', 'text3', 'text4']

As you can see the original array doesn't have to include every possible string in the pre-defined order.

The way I can think of doing it is looping through the array, see if there is 'text1' and if there is, put it in the ordered array. And do this for every string in the pre-defined order. But is there a better and neater way to do it?

Thank you.

Aucun commentaire:

Enregistrer un commentaire