{

Javascript tutorial Convert Array of primitive to Sets


In this post, I will blog several examples demonstrating how to convert Arrays with simple, Objects into Set types in JavaScript.

Javascript tutorial -  Convert Array of primitive,object to Sets example

The array contains data of any valid type in JavaScript. Data can be a primitive type or object of any type
Set is a new data structure introduced in ES6 which contains a unique collection of elements. Please see more about set datatype
Both are of a different type. We have to write a code to convert from one type to another type.
In my previous post, Learned how to convert the Set object to Array in JavaScript.

How to convert an Array primitive number or string to Set?

The Set constructor accepts an array of values using the new Set(array) syntax. Create a Set data using a new operator Following is an example of parse array of numbers, convert to set of data.

var myArray = [21, 3, 10];  
var mySet = new Set(myArray);  
console.log(mySet.size === myArray.length); //true  
console.log(myArray); //[ 21, 3, 10 ]  
console.log(mySet); //Set { 21, 3, 10 }  

Set does not allow duplicate elements. if the array contains duplicate values, the set only stores unique values. The following example returns false for equality of array and set type after conversion.

var myArray = [21, 3, 10,21];  
var mySet = new Set(myArray);  
console.log(mySet.size === myArray.length); //false  
console.log(myArray);//[ 21, 3, 10,21 ]  
console.log(mySet);//Set { 21, 3, 10 }  

Transfer Array of objects to Set keys and values

Array also contains objects, each object contain key and values Let’s see an example of transferring an array of plain objects to Set of keys and values Array with map function does iterate each element and add elements to an array, finally return the new array to set constructor.

let employees = [{ "id": 1, "name": "kiran" }, {  
    "id": 2,  
    "name": "franc"  
}]  
let idsSet = new Set(employees.map(element => element.id));  
let namesSet = new Set(employees.map(element => element.name));  

Output is

Set { 1, 2 }  
Set { 'kiran', 'franc' }  

Please like and share your feed if you like this post. Please comment your suggestions in below comment box.

THE BEST NEWSLETTER ANYWHERE
Join 6,000 subscribers and get a daily digest of full stack tutorials delivered to your inbox directly.No spam ever. Unsubscribe any time.

Similar Posts
Subscribe
You'll get a notification every time a post gets published here.