Array.map()

The Array.map() method is a concise way to run the logic of a provided callback function on every element of a particular array.

Syntax 📝

// using traditional function syntax
const newArrayFromMap = originalArray.map(function callback(currentValue[, index[, array]]) {
    // process each value in new array
})

// using arrow function syntax
const newArrayFromMap = originalArray.map((currentValue[, index[, array]]) => {
    // process each value in new array
})

Parameters

  • callback: The callback function will be used to process each element of the new array that will be returned. It will accept up to three arguments:
    • currentValue: The current element of the array that is to be operated on by the logic from with the callback function.
    • index Optional: The index of the current element that's being processed
    • array Optional: The original array that the map method was called upon.
  • thisArg Optional: If provided, thisArg will become the this value for callback

Real World Examples 🌎

Let's imagine you were creating an ecommerce platform and you needed to integrate a feature that allowed you to calculate the sales tax for each particular item in a user's shopping cart.

We already have some existing logic in our ecommerce platform as follows:

  • We know the user is located in Massachusetts, according to our userState variable.

  • Based off of userState, the salesTaxRate variable is set accordingly, in this case for Massachusetts it is equal to 6.25.

  • We are able to calculate the sales tax for each item in our calculateItemPriceWithSalesTax function assuming we pass an itemPrice and salesTaxRate as arguments.

Within the shoppingCart array, we have a number of objects that contain a particular item's name, price, and whether the item isTaxable.

In some states, such as Massachusetts, clothing is not taxable. So the shirt item that's in the user's shoppingCart will be tax exempt.

Using the Array.map() we can run some logic over each item within the shoppingCart, and if an item isTaxable, we can calculateItemPriceWithSalesTax accordingly. Otherwise, we will just return the item price without sales tax. We will then create a new shopping cart, shoppingCartWithSalesTaxAdded, which will contain a new array of objects, with an updated price for each taxable item.

You'll see that the Array.map() method is rather straight forward and very useful:

var shoppingCart = [{ name: "headphones", price: 49.99, isTaxable: true }, { name: "stickers", price: 8.99, isTaxable: true}, { name: "shirt", price: 19.99, isTaxable: false }];

var userState = "Massachusetts"; // user's state

var salesTaxRate = 6.25; // sales tax rate for user's state

var calculateItemPriceWithSalesTax = (itemPrice, salesTaxRate) => {
	
	itemPrice = itemPrice + (itemPrice * (salesTaxRate / 100))

	return parseFloat(itemPrice.toFixed(2)); // parse price into float & return only 2 decimal places

}

var shoppingCartWithSalesTaxAdded = shoppingCart.map((item) => {

    if (item.isTaxable) {

		// if item is taxable, calculate the item price with sales tax
		item.price = calculateItemPriceWithSalesTax(item.price, salesTaxRate);
        
        console.log('taxed item:', item)
		
        return item;

    } else {
        console.log('untaxed item:', item)
		// if item is not taxable, do not add tax
		return item;
		
    }
})

console.log(shoppingCartWithSalesTaxAdded)

// outputs [{name: "headphones", price: 53.11, isTaxable: true}, {name: "stickers", price: 9.55, isTaxable: true}, {name: "shirt", price: 19.99, isTaxable: false}]

Test this code in your browser console

Wrapping Up ✅

The Array.map() method is extremely powerful in that you're able to run a piece of logic over each item within an array. I personally use the Array.map() method almost daily!

Stay Tuned 📺

If you have any questions or improvements, or if you'd like to see additional examples, feel free to reach out to me anytime at tim@timwheeler.com. If you're enjoying my posts, please subscribe below! 👇