DEV Community

Aravind Sanjeev
Aravind Sanjeev

Posted on • Originally published at humaneer.org

5 Array Methods for Building a Shopping Website

An array in JavaScript is an object that can store a list of items. In this post, I will explain 5 must know JavaScript array methods and how to use them to create a shopping website.

PS: No, I am not literally creating a shopping website. This post will give you a practical glance over these array methods.

First, we create a list of product items using an array.

const products = [
  { Name: "White Shirt", Price: 20, addedToCart: false },
  { Name: "Black Jeans", Price: 35, addedToCart: false },
  { Name: "Leather Jacket", Price: 50, addedToCart: false },
  { Name: "Sweater", Price: 55, addedToCart: false },
  { Name: "Coat", Price: 80, addedToCart: false },
]
Enter fullscreen mode Exit fullscreen mode

We will stick to basic data like product name and the price.

Listing product items

When a user visits our site, we need to show a list of our poducts. Ideally, the product name is shown. To do that, we use the map() method.

The map() method iterates over each item in an array and returns another array. The new array is created with the results of a function which is called for each item in the array.

const Names = products.map(product => product.Name)

console.log(Names)

// [ White Shirt, Black Jeans, Leather Jacket, Sweater, Coat ]
Enter fullscreen mode Exit fullscreen mode

Since map() iterates over each item, the function is run for each product. The product variable store the product object and product.Name returns the names. Each name is automatically appended to the Names array after the end of each iteration. Now we have an array that list the name of each products.

Price filter

Filtering results with a price range is one of the most used features on an e-commerce site. To do that, we can use the filter() method.

The filter() method also iterates over each item in an array and creates a new array. However, the elements in the new array is selected based on a test.

The below code will filter out all the items that cost above 50.

const priceLessThan50 = products.filter(product => product.Price <= 50)

const priceLessThan50Names = priceLessThan50.map(product => product.Name)

console.log(priceLessThan50Names)

// [ White Shirt, Black Jeans, Leather Jacket ]
Enter fullscreen mode Exit fullscreen mode

Remember, filter() method will filter out every product that costs above 50. We use it in combination with the map() method to display the results.

You can get creative with filter() method. For example, you can filter the out of stock products.

Products per page

For accessibility reasons, it is convenient to have an option to increase or limit products per page. This can be easily done using the slice() method.

console.log(products.slice(0, 3))

/* 
[
  { Name: "White Shirt", Price: 20, addedToCart: false },
  { Name: "Black Jeans", Price: 35, addedToCart: false },
  { Name: "Leather Jacket", Price: 50, addedToCart: false },
]
*/
Enter fullscreen mode Exit fullscreen mode

Since slice() method only creates a shallow copy, you can write logic to recur it.

Add item to cart

To add an item to cart, we need to change the addedToCart status to true. Since we need to modify the property of each product object, we can use the forEach() method.

The forEach() method calls a function for each element in an array.

function cart(product) {
  if (
    product.Name == "White Shirt" ||
    product.Name == "Leather Jacket" ||
    product.Name == "Coat"
  ) {
    product.addedToCart = true
  }
}

products.forEach(cart)

console.log(products)

/* [
  { Name: "White Shirt", Price: 20, addedToCart: true },
  { Name: "Black Jeans", Price: 35, addedToCart: false },
  { Name: "Leather Jacket", Price: 50, addedToCart: true },
  { Name: "Sweater", Price: 55, addedToCart: false },
  { Name: "Coat", Price: 80, addedToCart: true },
] */
Enter fullscreen mode Exit fullscreen mode

I hard coded the product values, you can use your own logic.

Tip: You can use the addedToCart status to show different CSS. Also, you can use the same logic to remove something from the cart.

Final amount

At the checkout screen, we have to show the final amount. For this, we will need to do three things:

  1. Make an array of products that are added to the cart
  2. Extract the price of these products
  3. Sum them to get final amount

First we will make array of products that are added to the cart using filter.

const cartItems = products.filter(product => product.addedToCart == true)
Enter fullscreen mode Exit fullscreen mode

Next we will make an array of the prices using map.

const prices = cartItems.map(cartItem => cartItem.Price)

console.log(prices)

// [20, 50, 80]
Enter fullscreen mode Exit fullscreen mode

Now we will use the reduce() method to find the total.

The reduce() method is used to return a single value after processing an entire array.

const total = prices.reduce((m, n) => m + n)

console.log(total) // 150
Enter fullscreen mode Exit fullscreen mode

Here, m holds the previous value and n holds the current value. Initially, it will be 0 and 20 (first element). Then it will become 20 (0+20) and 50 (second element). Finally, it will become 70 (20 + 50) and 80 (third element) and return 150.

Anyone wishing to give arrays and its methods an in-depth look, I recomment this mdn article.

Discussion (2)

Collapse
pierrewahlberg profile image
Pierre Vahlberg

Interesting approach to demo these functions :) I hope any new devs do not build an actual webshop this way in the frontend, for many reasons (use a backend for anything that would need to be checked/validated against a database or handle big datasets when filtering and paginating)

Anyway, I like how this demonstrates a relatable problem where one could loop over products for different purposes!

I think .map, .filter and .reduce are the heaviest methods in my JS arsenal when it comes to crunching data, be it scrubbing data for DTOs, aggregating analytics, plucking values from datasets or calculating filtered sums. 👌

Collapse
aravsanj profile image
Aravind Sanjeev Author

Much thanks for your reply, Pierre. I also hope the same. I have built static e-commerce sites with very few products like this. Any serious software will need the logic to be written on backend. Also search functionality has to go to the backend for many good reasons.