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.

You can also check other posts on Javascript Add,Delete from Array

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 of data using a new operator.

Following is an example of parsing an array of numbers, and convert to a 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 }

How to Convert 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 a 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.