Array to Set JavaScript

What is an Array in JavaScript?

In JavaScript, an array is a specialized object designed to hold a group of data types that are comparable to one another. To put it differently, an array represents a compilation of like data types utilized for the purpose of storing various values or elements.

Utilizing an array in JavaScript allows us to arrange and retain similar categories of data efficiently. In JavaScript, the initial element of the array is located at index zero, while the subsequent element can be found at index 1, and this pattern continues consecutively.

Syntax

Example

var array = [1,2,3,4,5];

What is a Set in JavaScript?

In JavaScript, a set is a data structure that maintains a collection of distinct values. Within a set, duplicate values or elements are not permitted; however, it is possible to store various data types.

In JavaScript, when there is a duplicate or identical value within a set, only the initial occurrence will be retained in the set. To put it differently, a set functions as an object that permits the storage of unique values, ensuring that no element can be duplicated.

Syntax

Example

new Set ([it]);

How to Convert Array to Set in JavaScript?

In JavaScript, if we want to convert array to set then we need to use some methods. Some methods are as follows:

  • Map and add methods
  • Reduce method
  • Spread operator
  • Using map and add methods

In JavaScript, by utilizing the map function, we can invoke a specific function for every single element in an array without altering the original array itself. Additionally, through the add method, we can insert a new element containing the designated value.

Syntax

Example

array.map (function (current value, index, array), value)

To illustrate the functionality of the map and add methods in JavaScript, let’s consider a practical example:

Example:

Example

const array = [2, 3, 4, 3, 4, 5];

// Use the map() method to create an array of elements to add to the set

const elementsToAdd = array.map(element => element);

// Create a new set and use the add() method to add each element to the set

const set = new Set();

elementsToAdd.forEach(element => set.add(element));

// Log the set to the console

console.log("The converted array to set is", set);

Example

In the preceding illustration, we initialized an array and subsequently employed the map function to generate an array of items intended for inclusion in the set. Following this, we instantiated a new set and utilized the add method to incorporate each item into the set.

Following all these steps, we outputted the transformed array to the browser console for verification.

Output:

Using the reduce method

In JavaScript, the reduce method enables us to apply a function to the elements of an array, allowing us to derive a single, aggregated value. By utilizing the reduce method in JavaScript, we can pass the value corresponding to each array element into the function we have defined, leading to the generation of a consolidated result.

Syntax

Example

array.reduce(function(total, value, index, array)value)

To illustrate the functionality of the reduce method in JavaScript, let's consider an example:

Example

var array = [2, 3, 4, 4, 'Rohit'];

console.log("The given array is:", array);

var set = new Set();

array.reduce((_, item)=> set.add(item),null);

set.forEach(item => {

        console.log("the converted array to set is:", item);

    });

Explanation

In the preceding example, an array containing both integers and strings was generated and subsequently displayed. Following that, a set was established where the reduce function was employed, passing the variable item to the add method associated with the defined set. This operation culminates in condensing the initially created array into the distinct values of the set.

Output:

Using Spread Operator

In JavaScript, the spread operator allows us to duplicate all or select portions of an array into a different array. Put differently, the spread operator enables us to tap into the contents of iterable entities.

In JavaScript, an iterable item refers to any object that can be traversed using iteration, such as arrays, object literals, and strings.

Example

To gain a comprehensive understanding of the spread operator, let's examine this program as an illustrative example.

Example

const array = [2, 3, 4, 3, 4, 5];

// Use the spread operator to spread the array into a new set

const set = new Set([...array]);

// Log the set to the console

console.log("The converted array to set is", set);

Explanation

In the example provided above, we initiated an array. Following the creation of the array, we employed the spread operator to expand the array into a new set, and subsequently, we displayed the result using a console log statement.

Output:

Benefits of Converting Array to Sets

Transforming arrays into sets presents multiple benefits in JavaScript development.

Elimination of duplicate elements

In JavaScript, sets inherently eliminate duplicate entries, thereby maintaining the integrity of the data.

Improved performance

In JavaScript, sets offer improved access and lookup speeds when contrasted with arrays, particularly beneficial for more extensive collections.

Simplified data manipulation

In JavaScript, Sets provide several built-in methods for performing set operations, including union, intersection, and difference.

Input Required

This code uses input(). Please provide values below: