Monday, March 9, 2020

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

In this post, I will blog several examples demonstrating how to convert Arrays with simple, Objects into Set type 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 objects of any type
Set is a new data structure introduced in ES6 which contain a unique collection of elements. Please see more about set datatype
Both are of a different types. We have to write a code to convert from one type to another type.
In my previous post, Learned how to convert Set object to Array in JavaScript.

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

Set constructor accepts array of values using new Set(array) syntax. Create a Set data using 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 array contains duplicate values, set only stores unique values. The following example return 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 transfer array of plain objects to Set of keys and values Array with map function does iterates 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.

Related article


EmoticonEmoticon