How to use Lodash _.toArray() Method In Javascript
Lodash is an JavaScript library that allows us to use the _.toArray() method which accepets a value and convert it to an array.
NOTE: To use this approach, you need to install the lodash library into your local system using the npm i lodash command.
Syntax:
const arrayName = _.toArray(setName);
Example: The below code implements the _.toArray() method of the lodash library to convert a set into an array.
// Requiring the lodash library
const _ = require("lodash");
let set = new Set(['welcome', 'to', 'GFG']);
console.log('Set Elements: ', set);
// Use of _.toArray() method
console.log('Array Elements: ', _.toArray(set));
Output:
Set Elements: Set(3) { 'welcome', 'to', 'GFG' }
Array Elements: [ 'welcome', 'to', 'GFG' ]
How to convert Set to Array in JavaScript ?
To convert a Set into an Array, we need to know the main characteristics of a set. A set is a collection of unique items, i.e. no element can be repeated. Set in ES6 are ordered i.e. elements of the set can be iterated in the insertion order. Converting a Set to an Array in JavaScript is straightforward thanks to Sets’ unique element nature and ordered structure.
A set can be converted to an array in JavaScript in the following ways:
Table of Content
- 1. Using JavaScript Array.from() Method
- 2. Using JavaScript Spread Operator
- 3. Using JavaScript forEach() Method
- 4. Using Lodash _.toArray() Method
- 5. Using the Mapping Function
- Using JavaScript Array.prototype.map Method with Spread Operator