As a follow-up to my previous post about how to create comma separated strings from arrays, here’s another array tip.
Let’s take the previous example of the Tags array. Except this time, Tags contains the IDs, which correspond to the textual string.
Tags[0] = 23 Tags[1] = 42 Tags[2] = 314
Rather than write a for-loop to look up each value, let’s pretend we’ve already got a function getTagTextByID(), which accepts the tag ID, and returns the tag text.
Tags = Tags.map(getTagTextByID)
Now tags has the text for the tags.
Map is a fairly common function for operating on arrays. As with the previous tip, Map is available in many languages. PHP offers array_map(), and JavaScript offers Array.map(). Check your favorite language for this function, it makes code cleaner.
As an added bonus, Map has a starring role in MapReduce, Google’s favorite technique. Shouldn’t you get to know Map too?