javascript logo

This tutorial will demonstrate how to convert units of measurement with the javascript Array.map() method. The below examples are specific to converting a group of measurements from one unit to another with javascript. For example, if you need to convert a group of distances that were measured in miles to kilometers or a product weighed in ounces to pounds or maybe you need to convert a group of percentages to fractions. An array of these measurements can conveniently and quickly get converted with javascript’s Array.map() method.

The map() method is called as a prototype method of an array. The function passed to array.map() runs on every element in that array, and then returns a new array with the returned values.

The following examples convert distance, temperature, weight, and time to demonstrate some scenarios for when and how to use the Array.map() method.

  1. Convert Meters to Centimeters
  2. Convert Celsius to Fahrenheit
  3. Convert Kilograms to Grams
  4. Convert Years to Days

Let’s say we have an array of measurements in meters, but what we really need is an array of those measurements in centimeters. To convert from Meters to Centimeters multiply total meters by 100

Let’s take a look at an example using the map() method to convert an array of temperatures in Celsius to an array of temperatures in Fahrenheit. To convert temperatures in degrees Celsius to Fahrenheit, multiply by 1.8 and then add 32.

Let’s take a look at an example using the map() method to convert a array of weights in kilograms to an array in grams. To convert weight from Kilograms to grams, multiply by 1000

Lastly, let’s use the javascript map() method to convert an array of time in years to an array in days. To convert years to days, multiply years by 365 days

To summarize, javascripts Array.map() method is useful for converting a group of measurements with javascript. Whether you are looking to convert a group of distances, temperatures, weights, times or other units, Array.map() can handle the job. Array.map() goes much deeper and can handle many more use cases. Array.map() also has parameters passed in with the callback function including currentValue, index, and the array that .map() was called from. While the above examples map over an array of numbers, .map() can also be used with strings, objects, and other types stored within the array.

For a more in depth explanation of the Array.map() javascript method, checkout the Mozilla Developer Network map() method documentation.
MDN Array.prototype.map()