Set vs. Array in JavaScript: Understanding the Differences and Use Cases

JavaScript provides developers with several data structures to store and manipulate collections of values. Two commonly used data structures are sets and arrays. In this blog post, we’ll explore the differences between sets and arrays, their advantages and disadvantages, and some common use cases for each.

Arrays

An array is a collection of values that can be of any type, including strings, numbers, objects, and other arrays. Arrays are ordered, meaning that the elements are stored in a specific sequence and can be accessed by their index. An index is an integer value that starts from 0 and increments by 1 for each element in the array.

Here’s an example of an array that contains three strings:

const fruits = ['apple', 'banana', 'orange'];

We can access the elements of this array using their index:

console.log(fruits[0]); // 'apple'
console.log(fruits[1]); // 'banana'
console.log(fruits[2]); // 'orange'

Arrays have several advantages. They are very versatile and can be used to store collections of any type of value. They also have a wide range of methods that allow for efficient manipulation of the elements, such as push, pop, shift, unshift, splice, and sort. Arrays are a common data structure for many use cases, including:

  • Storing and manipulating lists of items, such as to-do lists, shopping lists, or lists of contacts.
  • Representing sequences of values, such as time series data or audio waveforms.
  • Implementing data structures such as stacks, queues, and hash tables.
  • Implementing algorithms such as sorting and searching.

Sets

A set is a collection of unique values, meaning that each value can only appear once in the set. Sets are not ordered, meaning that the elements are not stored in a specific sequence and cannot be accessed by their index. Instead, sets use a hash table to store the elements, which allows for efficient checking of membership (i.e., whether a value is in the set or not).

Here’s an example of a set that contains three strings:

const fruits = new Set(['apple', 'banana', 'orange']);

We can check if a value is in the set using the has method:

console.log(fruits.has('apple')); // true
console.log(fruits.has('kiwi')); // false

Sets have several advantages. They are optimized for checking if a value is present, as checking membership in a set is much faster than searching for an element in an array. Sets also have specialized methods for operations like union, intersection, and difference, which can be useful in certain scenarios. Some common use cases for sets include:

  • Keeping track of unique values in a collection, such as unique email addresses in a mailing list or unique product categories in a catalog.
  • Removing duplicates from an array, by converting the array to a set and then back to an array (since sets only contain unique values).
  • Performing set operations, such as finding the intersection of two sets or checking if one set is a subset of another.

Use Case: Unique SKU Count

One common use case where sets can be particularly useful is in counting the number of unique SKUs in a list of products. A SKU (stock keeping unit) is a unique identifier assigned to each product in a store’s inventory. When a store has a large inventory of products, it can be challenging to keep track of how many unique SKUs are currently in stock.

Here’s an example of how we could use a set to count the number of unique SKUs in a list of products:

const products = [
{name: 'Apple', sku: 'A001'},
{name: 'Banana', sku: 'B001'},
{name: 'Orange', sku: 'C001'},
{name: 'Grapes', sku: 'D001'},
const skus = new Set(); products.forEach((product)) => {skus.add(product.sku); });
console.log(skus.size);

In this example, we create an array of product objects, where each object has a name and a unique SKU. We then create a new set and iterate over each product in the array. For each product, we add its SKU to the set using the add method. Since sets only contain unique values, adding a SKU that already exists in the set will have no effect. Finally, we output the size of the set, which gives us the number of unique SKUs in the list of products.

Conclusion

In summary, sets and arrays are both useful data structures in JavaScript, each with its own advantages and disadvantages. Arrays are ordered and can contain duplicate values, while sets are unordered and contain only unique values. Arrays have a wide range of methods for efficient manipulation of the elements, while sets are optimized for checking membership and have specialized methods for set operations. When choosing between an array and a set for a particular use case, consider the requirements for ordering and uniqueness of the values, as well as the efficiency of the required operations.

Share

Table of Contents

More To Explore

Top Google Ads Consultants

In the ever-evolving world of digital advertising, choosing the right Google Ads consultant can make or break your return on ad spend (ROAS).

Whether you’re a fintech startup, eCommerce brand, or B2B service provider, here’s our updated list of the top Google Ads consultants.

Top Financial Services Marketing Agencies in Toronto

Navigating the world of financial marketing requires more than a creative ad—it takes strategy, compliance, and a partner who truly understands your industry. Whether you’re a fintech startup, a wealth management firm, or a national bank, choosing the right agency can transform your brand’s visibility, trust, and growth.

Understanding ‘Noindex’ Tags: Definition, Purpose, Impacts, and Use Cases

In the vast realm of SEO (Search Engine Optimization), few tags carry as much weight and significance as the ‘noindex’ tag. It’s a simple directive, but its implications can be profound. If you’ve ever wondered how to prevent search engines from indexing specific pages on your site, or why you’d want to do so, this post will shed light on the topic.

Let’s Level Up

Ready to take your business to the next level? Partner with Welby Consulting to unlock the full potential of your data and digital presence.

We're Here To Help

Get In Touch

Feel free to contact us, and we will be more than happy to answer all of your questions.