logo

Com convertir Set a Array en JavaScript?

Per convertir a Conjunt en un Matriu , hem de conèixer les característiques principals d'un conjunt. A conjunt és una col·lecció d'elements únics, és a dir, no es pot repetir cap element. Conjunt a ES6 estan ordenats, és a dir, elements de la conjunt es pot repetir en l'ordre d'inserció. Convertir un conjunt en una matriu en JavaScript és senzill gràcies a la naturalesa d'elements únics i a l'estructura ordenada de Sets.

convert-set-to-array

convertir Set a Array en JavaScript



A conjunt es pot convertir en una matriu en JavaScript de les maneres següents:

Taula de contingut

1. Utilitzant el mètode JavaScript Array.from().

JavaScript Array.from() Mètode retorna una nova matriu d'una matriu, objecte o altres objectes iterables com Map, Set, etc. Pren el conjunt com a paràmetre i el converteix en una matriu.



Sintaxi:

const arrayName = Array.from(setName);>

Exemple: T el seu exemple converteix un conjunt en una matriu utilitzant el Mètode Array.from().

uri vs url
Javascript
// Creating array from input string const mySet = new Set([1, 1, 2, 3, 4, 4, 5, 6, 5]); console.log('Elements in the set are: ', mySet); let myArr = Array.from(mySet); // Display output console.log('Elements in the Array created using Set are: ', myArr);>

Sortida
Elements in the set are: Set(6) { 1, 2, 3, 4, 5, 6 } Elements in the Array created using Set are: [ 1, 2, 3, 4, 5, 6 ]>

2. Ús de JavaScript Spread Operator

El Operador de propagació de JavaScript es pot utilitzar per desestructurar els elements de la matriu i després assignar-los a la nova variable en forma de matriu.

format de cadena java

Sintaxi:

const arrayName = [...setName];>

Exemple: El codi següent converteix un conjunt en una matriu utilitzant el operador de propagació .



Javascript
// Input set let mySet = new Set(['GFG', 'JS']); console.log('Elements in the set are: ', mySet); // Convert using spread operator let myArr = [...mySet]; // Display output console.log('Elements in the Array created using Set are: ', myArr);>

Sortida
Elements in the set are: Set(2) { 'GFG', 'JS' } Elements in the Array created using Set are: [ 'GFG', 'JS' ]>

3. Utilitzant el mètode JavaScript forEach().

El mètode arr.forEach(). crida a la funció proporcionada una vegada per a cada element del conjunt on s'envien a una matriu mitjançant el mètode push().

Sintaxi:

 setName.forEach((ele)=>{ arrayName.push(ell); });>

Exemple: L'exemple de codi següent utilitza el mètode forEach(). per convertir un conjunt en una matriu.

Javascript
// Create input set let newSet = new Set(); let arr = []; newSet.add('Geeks'); newSet.add('for'); // Duplicate item newSet.add('Geeks'); console.log('Set Elements: ', newSet); let someFunction = function (val1) {  arr.push(val1); }; newSet.forEach(someFunction); // Display output console.log('Array Elements: ' + arr);>

Sortida
Set Elements: Set(2) { 'Geeks', 'for' } Array Elements: Geeks,for>

4. Utilitzant el mètode Lodash _.toArray().

Lodash és una biblioteca de JavaScript que ens permet utilitzar el _.toArray() mètode que accepta un valor i el converteix en una matriu.

NOTA: Per utilitzar aquest enfocament, heu d'instal·lar la biblioteca lodash al vostre sistema local mitjançant l' npm i lodash comandament.

Sintaxi:

const arrayName = _.toArray(setName);>

Exemple: El codi següent implementa el mètode _.toArray() de la biblioteca lodash per convertir un conjunt en una matriu.

Javascript
// 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));>

Sortida:

Set Elements: Set(3) { 'welcome', 'to', 'GFG' } Array Elements: [ 'welcome', 'to', 'GFG' ]>

5. Utilitzant el mètode Array.from() amb una funció de mapeig

Mentre que Mètode Array.from(). s'utilitza habitualment per convertir iterables com conjunts en matrius, també permet l'ús d'una funció de mapeig. Aquesta funció de mapeig pot ser útil per transformar cada element del conjunt durant el procés de conversió.

Sintaxi:

const arrayName = Array.from(setName, mapFunction);>

Exemple: Aquest exemple mostra com utilitzar Array.from() amb una funció de mapeig per convertir un conjunt en una matriu amb elements modificats.

Diagrama del model e-r
JavaScript
// Create a set with numerical values const numSet = new Set([1, 2, 3, 4, 5]); // Convert the set to an array, doubling each element const doubledArray = Array.from(numSet, x =>x * 2); console.log('Matriu duplicada:', matriu doble);>>>  
Sortida
Doubled Array: [ 2, 4, 6, 8, 10 ]>

Utilitzant el mètode JavaScript Array.prototype.map amb l'operador Spread

Un altre enfocament per convertir un conjunt en una matriu en JavaScript és combinar el mètode del mapa amb l'operador de propagació. Aquest mètode permet la transformació d'elements durant el procés de conversió, de manera similar a Array.from() amb una funció de mapeig, però utilitzant una sintaxi diferent.

Sintaxi :

Exemple: En aquest exemple, convertirem un conjunt en una matriu i aplicarem una transformació a cada element mitjançant el mètode map.

JavaScript
// Create a set with string values const stringSet = new Set(['a', 'b', 'c', 'd']); // Convert the set to an array, appending a suffix to each element const suffixedArray = [...stringSet].map(x =>x + '_sufix'); console.log('Sufixed Array:', suffixedArray);>>>  
Sortida