DEV Community

avinash-repo
avinash-repo

Posted on

Array Vs Set

Certainly, here are examples illustrating the use of Set and WeakSet in ES6:

https://onecompiler.com/javascript/423ctrkr3

Set Example:

// Creating a Set
const mySet = new Set();

// Adding elements to the Set
mySet.add(1);
mySet.add('Hello');
mySet.add({ key: 'value' });


// Checking for existence
console.log(mySet.has(1)); // true  isme kewal unique value hi show krta hai matalab Set me kewal 2 value same hogi to ek baar hi show krega


// Iterating through the Set
mySet.forEach((item) => {
    console.log(item);
});

// Deleting an element
mySet.delete('Hello');

// Size of the Set
console.log(mySet.size); // 2
Enter fullscreen mode Exit fullscreen mode

In this example, a Set is created and populated with various data types. It demonstrates adding, checking for existence, iterating, deleting, and obtaining the size of the set.

WeakSet Example:

// Creating objects
let obj1 = { name: 'Object 1' };
let obj2 = { name: 'Object 2' };

// Creating a WeakSet
const myWeakSet = new WeakSet();

// Adding objects to the WeakSet
myWeakSet.add(obj1);
myWeakSet.add(obj2);

// Checking for existence
console.log(myWeakSet.has(obj1)); // true

// Removing an object (Not possible directly; relies on external references)

// Letting an object go out of scope
obj1 = null;

// Checking for existence after object is out of scope
console.log(myWeakSet.has(obj1)); // false
Enter fullscreen mode Exit fullscreen mode

In this WeakSet example, two objects are added to the WeakSet. Importantly, when an object goes out of scope and is no longer referenced externally, it becomes eligible for garbage collection, and the corresponding entry in the WeakSet is automatically removed. The WeakSet is useful in scenarios where the lifecycle of elements should be tied to external references.

The choice between Set and Array in JavaScript depends on the specific requirements of your data and the operations you need to perform. Here's a comparison between Set and Array:

Set:

  1. Uniqueness:

    • Set:
      • Enforces uniqueness of elements. It cannot contain duplicate values.
    • Array:
      • Allows duplicate values. Each element is distinct, and repetition is possible.
  2. Order:

    • Set:
      • Maintains the order of insertion of elements.
    • Array:
      • Preserves the order of elements based on their indices.
  3. Use Case:

    • Set:
      • Ideal when ensuring unique values or checking membership efficiently.
    • Array:
      • Suitable for ordered collections where duplicates are allowed and random access to elements is necessary.
  4. Methods:

    • Set:
      • Provides methods like add, delete, has, and forEach for manipulating elements.
    • Array:
      • Offers a wide range of methods for manipulation, such as push, pop, splice, and map, catering to various array operations.

Example - Set:

const mySet = new Set();

mySet.add(1);
mySet.add(2);
mySet.add(3);

console.log(mySet.has(2)); // true
console.log(mySet.size);    // 3
Enter fullscreen mode Exit fullscreen mode

Example - Array:

const myArray = [1, 2, 3, 2];

console.log(myArray.includes(2)); // true
console.log(myArray.length);       // 4
Enter fullscreen mode Exit fullscreen mode

In the Set example, duplicate values are automatically ignored. In the Array example, duplicate values are retained.

When to Choose:

  • Use Set when you need a collection of unique values and the order of insertion matters.
  • Use Array when you require an ordered collection, and duplicates are acceptable, or when you need to perform various array-specific operations.

In summary, while Set is specialized for unique values with efficient membership checks, Array is more versatile and appropriate for scenarios where ordering and duplicates are part of the requirements.

Let's analyze the provided JavaScript code step by step:

  1. Creating a Set and Adding Elements:
   const mySet = new Set();

   mySet.add(1);
   mySet.add('Hello');
   mySet.add({ key: 'value' });
   mySet.add([{ key1: 'value1', key2: 'value1-2' }]);
   mySet.add(1);
   mySet.add('Hello');
Enter fullscreen mode Exit fullscreen mode

This code initializes a Set named mySet and adds various elements, including numbers, strings, and objects. Note that duplicates are automatically ignored in a Set.

  1. Converting Array to Set:
   let newArray=[1,2,3,44,5,2,1];
   newArray=new Set(newArray);

   console.log("Line18-", [...newArray]);
Enter fullscreen mode Exit fullscreen mode

The array newArray is converted to a Set, and the spread operator ([...newArray]) is used to convert it back to an array. This demonstrates how a Set automatically handles duplicate values.

  1. Checking for Existence and Iterating through the Set:
   console.log("Line23-", mySet.has(1)); // true

   mySet.forEach((item) => {
       console.log(item);
   });
Enter fullscreen mode Exit fullscreen mode

The code checks for the existence of the value 1 in the Set using has(). It then iterates through the Set using forEach().

  1. Deleting an Element and Getting the Size:
   mySet.delete('Hello');
   console.log("Line34-", mySet.size); // 2
Enter fullscreen mode Exit fullscreen mode

The code deletes the value 'Hello' from the Set and retrieves its size.

  1. Exceptional Case with Objects:
   const mySett = new Set();
   mySett.add([{ key1: 'value1', key2: 'value1-2' }]);
   mySett.add([{ key1: 'value1', key2: 'value1-2' }]);
   console.log("Line40-", mySett);
Enter fullscreen mode Exit fullscreen mode

This part illustrates that even though the array elements contain the same values, they are treated as distinct objects within the Set. Each object reference is unique.

  1. Converting Array with Nested Arrays to Set:
  let newArray1=[1,[2,4,4,5,2],3,44,5,2,1,44,[2,3,45,44],[2,3,45,44]]
newArray1=new Set(newArray1)
console.log("Line44-",newArray1)
Enter fullscreen mode Exit fullscreen mode

Similar to the previous example, this part demonstrates that a Set treats nested arrays as distinct elements. Duplicates are not ignored based on the values within the nested arrays.

The provided code showcases various aspects of working with a Set in JavaScript, emphasizing uniqueness and automatic handling of duplicates. Additionally, it illustrates the behavior with objects and nested arrays within a Set.

Top comments (0)