Is set data structure is similar to an array in JavaScript?

JavaScript Set Data Structure

In Javascript, the set is a data structure that can hold a collection of values. The values however must be unique. The set can contain a mix of different data types. You can store strings, booleans, numbers, or even objects all in the same set. Sets are dynamically sized. You don’t have to declare the size of a set before creating it. It doesn’t maintain insertion order. Sets are iterable. We can use a for loop.

Sets Vs array

A lot of these characteristics are similar to the array. So, let’s see the differences between sets and arrays.

  1. Arrays can contain duplicate values whereas Sets cannot.
  2. Insertion order is maintained in arrays but it is not the case with sets.
  3. Searching and deleting an element in the set is faster compared to arrays.

Example of set:

  • To create a new set, we see the set constructor as in the below code.
    const set = new Set();
  • The constructor optionally accepts an array as its argument, so let’s pass in an array of three numbers:
    const set = new Set([1,2,3]);
  • To log value we can use the for of loop to iterate over the set, like:
    for (const item of set){
     console.log(item)
    }

    javascript set data structure

  • To add a new value, we can use the add() method, we can write the code like this:
    set.add(4);

     

  • If we try to add a duplicate value, the set will ignore that value. For example, if we add the value 4 again to set, it displays only once in the console.
    const set = new Set([1,2,3]);
    set.add(4)
    set.add(4)
    
    for (const item of set){
      console.log(item)
    }

Output:javascript set data structure

  • To delete particular values in the set, you can use of the delete() method and pass the value which values you delete.
    set.delete(4)
  • To delete all values in the set, you can make use of the clear method.
    set.clear()

Leave a Reply