Skip to main content

Posts

Showing posts from March, 2016

JavaScript (and Python): Mapping Array/List of Numbers to Strings and the Other Way Round

Convert All Items to String For instance, we have this object : [0, 1, 2, 3, 4, 5] In JavaScript, it's called array and in Python it's a list . Method in JavaScript We can use map() . var input = [0, 1, 2, 3, 4, 5]; var converted = input.map(function (item) { // Convert to string and return it to the new array. return item.toString(); }); Variable converted now consists of all members of variable input , but each of them is now a string type. Or more concise: var converted = input.map(String); Notice the uppercase S in String ? That's because String is a function ➡️ Automatically applies the conversion to each item. Method in Python Also using similar method keyword, map() but then it is wrapped in list() : list(map(str, input)) Usage: input = [0, 1, 2, 3, 4, 5] converted = list(map(str, input)) Or, the generic method in Python: converted = [str(item) for item in input] The str() is to convert anything to string . The ite...
Monkey Raptor uses cookies or biscuits 🍪 for analytics, functionality, and advertisements. More info in Privacy Policy