Skip to main content

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:

In JavaScript, it's called array and in Python it's a list.


Method in JavaScript

We can use map().

Variable converted now consists of all members of variable input, but each of them is now a string type.

Or more concise:

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():

Usage:

Or, the generic method in Python:

  • The str() is to convert anything to string.
  • The item is each member of variable input.
  • The input is the input variable (list) we want to convert.
  • And the square brackets, [...], are to initiate the new list.

Convert All Items to Number

For instance, we have this object:

It has string, number, object, and array.

Method in JavaScript

We still implement map(), but now we use Number as the callback (transform) function.

That looks awful for mixed types of items.

To specifically extract the number part, we can implement parseInt(string, radix).

The radix is optional. If it is left empty, the radix will be inferred based on string's value. Be careful — this does not always default to 10 ⚠️ More at MDN

Or parseFloat(string):

Or using custom RegExp:

Method in Python

Still using map() wrapped with list, but the transformer is using int or float. In this scenario, it is not recommended to use pure int or float because I made an absolute menace of an input.

We should use custom regular expression to do that:

On the above example, the list is converted into string, by using str(input). Then findall() transformed that string into list (of found patterns). And then the string to number (integer) mapping begins — the map() function.

But, for scattered digits, e.g. the number patterns for each member is separated by non-digit, and we need to get the first found number pattern (index 0), we can substitute the method with this:

Or this:

Either one is valid.


Thank you for visiting. I hope this post has useful information.

PLATY
Last modified on

Comments

Monkey Raptor uses cookies or biscuits πŸͺ for analytics, functionality, and advertisements. More info in Privacy Policy