Skip to main content

How to work with Set in JavaScript

Understanding JavaScript Sets

Set in JavaScript is an unordered collection of unique values. We can examine the size of the set using .size method. Notice that the set is unordered, and we can't guarantee that elements will be shown in the order we added them.

Sets work similarly to JavaScript objects but are designed for uniqueness. They use hashing, a way to convert a given pearl into a unique code, which facilitates rapid storage and retrieval. When checking if an item is in a Set, JavaScript computes its hash code to locate it, much like a map leading to a treasure. Sets have numerous practical uses in database management, data analysis, and more.

Problem 1: Check if Two Sets are Disjoint

Let's begin by considering the function, areDisjoint which takes two arrays and determines if they are disjoint, meaning they have no elements in common. This is crucial when analysing datasets for overlapping values, similar to ensuring that two puzzle pieces from different puzzles don't fit together. Think of two companies looking to cross-promote products but wishing to target customers who have yet to interact with both brands. Ensuring that their promotional efforts are disjoint becomes essential

Naive Approach

A naive approach would be to iterate over every element in the first array and, for each one, check every element in the second array for a match. This could be likened to standing at the junction of two busy streets and comparing every passerby on one side with every passerby on the other, looking for twins. The time cost grows prohibitively with the number of "passersby," making this method inefficient for larger datasets.

Efficient Solution Building

Consider a scenario with a list of names and a super-fast scanner that can immediately tell you whether a name is on the list. In JavaScript terms, this is what Sets offer via their has method — a way to check presence in constant time.

Let's build the solution, with this analogy in mind, step by step:

  1. Transfer the elements of one array into our super-fast scanner, a.k.a. a Set called set1.

  2. Feed names from the other array to the scanner using the .some() method to check if set1 can find a match. The some() method tests whether at least one element in the set passes the test implemented by the provided function.

  3. Since we want to determine whether there are no twins (common elements), we invert the result of .some() because it returns true if it finds at least one match.



Problem 2: Remove Duplicates in an Array

Now, we move on to a common data-cleaning problem: removing duplicates from an array. Consider a librarian cataloging books; duplicates waste space and need clarification. Like the librarian, we want our array to contain unique entries.

Approaches

The naive approach would involve creating a new list and adding only those items that aren't present, akin to checking each book against the entire catalogue before shelving it. This method is impractical for a library of any considerable size due to its squared time complexity. Let's consider the efficient approach. Enter JavaScript Sets, which adheres to the principle that "each member is unique." By converting our array into a Set, we automatically remove duplicates.

Solution Building

Let's look at how we can neatly apply this in code:

  1. First, we create a Set from our array. We had an assistant who automatically filtered out duplicate names from our lists.

  2. Then, we convert our Set, now containing unique names, back into an array, ready for use in our guest list system.



Unraveling Uniqueness and Anagram Mysteries with JavaScript Sets

Problem 1: Unique Echo

Picture this: you're given a vast list of words, and you must identify the final word that stands proudly solitary — the last word that is not repeated. Imagine sorting through a database of unique identifiers and finding one identifier towards the end of the list that is unlike any others.

Naive Approach

The straightforward approach would be to examine each word in reverse, comparing it to every other word for uniqueness. This brute-force method would result in poor time complexity, which is less than ideal for large datasets.

Efficient Approach

We can use two Set instances: wordsSet to maintain unique words and duplicatesSet to keep track of duplicate words. By the end, we can remove all duplicated words from wordsSet to achieve our goal. Here is how to use Set to solve the problem:

Create a Set instance to store unique words:



Initialize another Set to monitor duplicates:



Iterate the word array, filling wordsSet and duplicatesSet:


Use a loop to remove all duplicated words from wordsSet:


Now, wordsSet only contains unique words. Find the last unique word by iterating through the original word list from the end:


And finally, return the last unique word:


This efficient approach, with a time complexity closer to O(n), is far superior to the naive method and showcases your proficiency at solving algorithmic problems with JavaScript's Set

Problem 2: Anagram Matcher

Now, imagine a different scenario in which you have two arrays of strings, and your task is to find all the words from the first array that have an anagram in the second array.

Efficient Approach

We'll create a unique signature for each word by sorting its characters and then compare these signatures for matches. We'll use Set to store signatures for efficient access.

Solution Building

Let's break down the anagram matcher:

Construct a function to create sorted character signatures from the input string:


Store these sorted characters from array2 in a Set for fast lookup:

For each word in array1, check for its sorted signature in the Set and track the found anagrams:


The Array result stores the matches, ensuring that we return anagrams.

Our final step is to return the list of anagrams found:


By utilizing Sets in this manner, we achieve efficient anagram checking with reduced complexity, considering both the O(mlogm) character sorting for each word and the O(n) comparison for n words.


Comments

Popular posts from this blog

JavaScript Maps

Dive Into JavaScript Maps A Map stores data as key-value pairs. We'll recall how to create Maps, implement them, and delve into the details of their memory management. Understanding JavaScript Maps Maps are versatile data structures in JavaScript. They store key-value pairs and accept any data type as a key — even objects and functions! Here is how we create an empty Map: let myMap = new Map(); // creates an empty Map Here, myMap is a new JavaScript Map, eagerly awaiting to store your keys and values. Meander Through Map Methods Maps provide some essential built-in methods: set(key, value): Stores a key-value pair. get(key): Retrieves the value of a key. has(key): Checks if a key exists and returns true or false. delete(key): Erases a key-value pair. size: Returns the count of key-value pairs. To gain a better understanding, let's apply these methods: let myMap = new Map(); // Add pairs with set myMap.set('apples', 10); // Adds a new pair myMap.set('bananas', 6...

The Synergy Between DevOps and Agile Methodologies

When it comes to modern software development practices, two methodologies have gained significant traction in recent years: DevOps and Agile. While they are distinct in their approaches, DevOps and Agile share common goals of improving collaboration, efficiency, and quality in software development processes. Understanding DevOps DevOps  is a set of practices that combines software development (Dev) and IT operations (Ops) to shorten the systems development life cycle and provide continuous delivery of high-quality software. It emphasizes collaboration, automation, and monitoring throughout the software delivery process. Key principles of DevOps include: Automation of processes Continuous integration and delivery Monitoring and feedback loops Collaboration between teams Exploring Agile Methodologies Agile  is an iterative approach to software development that focuses on delivering value to customers through incremental and iterative development. Agile methodologies promote adap...