JavaScript Set To Array Conversion

JavaScript Set To Array Conversion | You must understand the essential properties of a set to transform a set into an array. A set is a collection of specific items in which no element can occur more than once. Sets in ES6 are ordered, and you can iterate their components in the order of insertion.

In JavaScript, you can transform a set into an array in the following ways:-

  • Using Array.form()
  • Using Spread Operator
  • Using forEach() method

JavaScript Set To Array Using Array.form()

The JavaScript method Array.from() creates a new Array from an array, much like an object would, or from iterable objects, like Map, Set, etc.

Syntax:-
Array.from(arrayLike object);

Example: Using the Array.from() method to convert set to array in JavaScript.

const set = new Set(["cat", "dog", "horse"]);
const arr = Array.from(set);

console.log(arr);
console.log(typeof arr);
console.log(arr.length);

Output:-

[ ‘cat’, ‘dog’, ‘horse’ ]
object
3

Set To Array in JavaScript Using Spread Operator

Using the spread operator, we can also turn a Set into an array.

Syntax:-
var variableName = […value]; 

Convert JavaScript Set to Array Using Spread Operator

const set = new Set(["cat", "dog", "horse"]);
const arr = [...set];

console.log(arr);
console.log(typeof arr);
console.log(arr.length);

Output:-

[ ‘cat’, ‘dog’, ‘horse’ ]
object
3

JavaScript Set To Array Using forEach() Method

The arr.forEach() method in JavaScript calls the supplied function once for each array element. By using forEach() method, you will transform a set into an array in this example.

var kpSet = new Set();
var kpArray = [];

kpSet.add("Know");
kpSet.add("Program");
kpSet.add("JS");
// duplicate item
kpSet.add("Know");

var setToArray = function (val1, val2, setItself) {
  kpArray.push(val1);
};

kpSet.forEach(setToArray);

console.log("Array: " + kpArray);
console.log(typeof kpArray);
console.log(kpArray.length);

Output:-

Array: Know, Program, JS
object
3

Since the set stores only unique elements therefore the “kpSet” stored only 3 elements. And after the conversion of the set to array the array contains 3 elements. Also see:- JavaScript Array pop() Method

If you enjoyed this post, share it with your friends. Do you want to share more information about the topic discussed above or do you find anything incorrect? Let us know in the comments. Thank you!

Leave a Comment

Your email address will not be published. Required fields are marked *