Sumário

O objeto Set permite que você armazene valores únicos de qualquer tipo, desde valores primitivos a referências a objetos.

Sintaxe

 new Set([iterable]);

Parâmetros

iterable
Se um objeto iterável é passado, todos os seus elementos serão adicionados ao novo Set. Se tal parâmetro não for específicado, ou se seu valor for null, o novo Set estará vazio.

Descrição

Objetos Set são coleções de valores nas quais é possível iterar os elementos em ordem de inserção. Um valor no Set pode ocorrer apenas uma vez; ele é único na coleção do Set.

Igualdade de valores

Como cada valor no Set deve ser único, a igualdade será checada e não é baseada no mesmo algoritmo que aquele usado no operador ===. Especificamente, para Sets, +0 (que é exatamente igual a - 0) e - 0 são valores diferentes. No entanto, isto foi modificado na última especificação ECMAScript 2015. Iniciado com o Gecko 29.0 (Firefox 29 / Thunderbird 29 / SeaMonkey 2.26) (bug 952870) e pelo  recent nightly Chrome, +0 e -0 são tratados com sendo o mesmo valor em objetos conjunto (Set). Também, NaN e undefined podem ser armazenados em um conjunto Set.

Propriedades

Set.length
O valor da propriedade comprimento é 0.
Para contar o número de elementos de um Set, use Set.prototype.size.
get Set[@@species]
A função construtora usada para criar objetos derivados.
Set.prototype
Representa o prototype do constructor do Set. Permite a adição de propriedades para todos os objetos do tipo Set.

Instâncias Set 

Todas as instâncias de Set herdam de Set.prototype.

Propriedades

Métodos

Exemplos

Utilizando o objeto Set

var meuSet = new Set();

meuSet.add(1);
meuSet.add(5);
meuSet.add("texto");
var o = {a: 1, b: 2};
meuSet.add(o);

meuSet.add({a: 1, b: 2}); // o está referenciando outro objeto

meuSet.has(1); // true
meuSet.has(3); // false, 3 não foi adicionado ao set (Conjunto)
meuSet.has(5);              // true
meuSet.has(Math.sqrt(25));  // true
meuSet.has("Texto".toLowerCase()); // true
meuSet.has(o); // true

meuSet.size; // 3

meuSet.delete(5); // remove 5 do set
meuSet.has(5);    // false, 5 já foi removido

meuSet.size; // 2, nós simplesmente removemos um valor

Iterando objetos Set

// iterar sobre os itens em set
// loga os itens na ordem: 1, "texto" 
for (let item of meuSet) console.log(item);

// loga os itens na ordem: 1, "texto" 
for (let item of meuSet.keys()) console.log(item);
 
// loga os itens na ordem: 1, "texto" 
for (let item of meuSet.values()) console.log(item);

// loga os itens na ordem: 1, "texto" 
//(key e value são os mesmos aqui)
for (let [key, value] of meuSet.entries()) console.log(key);

// converte Set para um Array
var meuArr = [v for (v of mySet)]; // [1, "some text"]

// o seguinte também funcionará se for executado em um documento HTML
mySet.add(document.body);
mySet.has(document.querySelector("body")); // true

// a conversão entre Set e Array
mySet2 = Set([1,2,3,4]);
mySet2.size; // 4
[...mySet2]; // [1,2,3,4]

// intersecção pode ser simulado via 
var intersection = new Set([x for (x of set1) if (set2.has(x))]);

// Iterar entradas set com forEach
meuSet.forEach(function(value) {
  console.log(value);
});

// 1
// 2
// 3
// 4

Implementando operações básicas entre conjuntos

function isSuperset(set, subset) {
    for (var elem of subset) {
        if (!set.has(elem)) {
            return false;
        }
    }
    return true;
}

function uniao(setA, setB) {
    var _uniao = new Set(setA);
    for (var elem of setB) {
        _uniao.add(elem);
    }
    return _uniao;
}

function interseccao(setA, setB) {
    var _interseccao = new Set();
    for (var elem of setB) {
        if (setA.has(elem)) {
            _interseccao.add(elem);
        }
    }
    return _interseccao;
}

function diferencaSimetrica(setA, setB) {
    var _diferenca = new Set(setA);
    for (var elem of setB) {
        if (_diferenca.has(elem)) {
            _diferenca.delete(elem);
        } else {
            _diferenca.add(elem);
        }
    }
    return _diferenca;
}

function diferenca(setA, setB) {
    var _diferenca = new Set(setA);
    for (var elem of setB) {
        _diferenca.delete(elem);
    }
    return _diferenca;
}

//Exemplos
var setA = new Set([1, 2, 3, 4]),
    setB = new Set([2, 3]),
    setC = new Set([3, 4, 5, 6]);

isSuperset(setA, setB); // => true
uniao(setA, setC); // => Set [1, 2, 3, 4, 5, 6]
interseccao(setA, setC); // => Set [3, 4]
diferencaSimetrica(setA, setC); // => Set [1, 2, 5, 6]
diferenca(setA, setC); // => Set [1, 2]

Relação com objetos Array 

var myArray = ["value1", "value2", "value3"];

// Use o construtor regular de Set para transformar um array dentro de um Set
var mySet = new Set(myArray);

mySet.has("value1"); // retorna true

// Use o operador de propagação para transformar um Set em um Array.
alert(uneval([...mySet])); // Irá mostrar-lhe exatamente o mesmo Array como myArray

Removendo elementos duplicados de um Array

// Use para remover elementos duplicados de um Array 
 
const numeros = [2,3,4,4,2,3,3,4,4,5,5,6,6,7,5,32,3,4,5]
 
console.log([...new Set(numeros)]) 

// [2, 3, 4, 5, 6, 7, 32]

Relação com objetos String

var texto = 'India';

var meuSet = new Set(texto);  // Set ['I', 'n', 'd', 'i', 'a']
meuSet.size;  // 5

Especificações

Especificação Status Comentário
ECMAScript 2015 (6th Edition, ECMA-262)
The definition of 'Set' in that specification.
Padrão Definição inicial.
ECMAScript Latest Draft (ECMA-262)
The definition of 'Set' in that specification.
Rascunho  

Compatibilidade de navegador (Browser)

Update compatibility data on GitHub
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariAndroid webviewChrome for AndroidEdge MobileFirefox for AndroidOpera for AndroidSafari on iOSSamsung InternetNode.js
SetChrome Full support 38Edge Full support 12Firefox Full support 13IE Full support 11Opera Full support 25Safari Full support 8WebView Android Full support 38Chrome Android Full support 38Edge Mobile Full support 12Firefox Android Full support 14Opera Android Full support 25Safari iOS Full support 8Samsung Internet Android Full support Yesnodejs Full support 0.12
Full support 0.12
Full support 0.10
Disabled
Disabled From version 0.10: this feature is behind the --harmony runtime flag.
new Set(iterable)Chrome Full support 38Edge Full support 12Firefox Full support 13IE No support NoOpera Full support 25Safari Full support 9WebView Android Full support 38Chrome Android Full support 38Edge Mobile Full support 12Firefox Android Full support 14Opera Android Full support 25Safari iOS Full support 9Samsung Internet Android Full support Yesnodejs Full support 0.12
new Set(null)Chrome Full support YesEdge Full support 12Firefox Full support 37IE Full support 11Opera Full support YesSafari Full support 9WebView Android Full support YesChrome Android Full support YesEdge Mobile Full support 12Firefox Android Full support 37Opera Android Full support YesSafari iOS Full support 9Samsung Internet Android Full support Yesnodejs Full support 0.12
Full support 0.12
Full support 0.10
Disabled
Disabled From version 0.10: this feature is behind the --harmony runtime flag.
Set() without new throwsChrome Full support YesEdge Full support 12Firefox Full support 42IE Full support 11Opera Full support YesSafari Full support 9WebView Android Full support YesChrome Android Full support YesEdge Mobile Full support 12Firefox Android Full support 42Opera Android Full support YesSafari iOS Full support 9Samsung Internet Android Full support Yesnodejs Full support 0.12
Key equality for -0 and 0Chrome Full support 38Edge Full support 12Firefox Full support 29IE No support NoOpera Full support 25Safari Full support 9WebView Android Full support 38Chrome Android Full support 38Edge Mobile Full support 12Firefox Android Full support 29Opera Android Full support 25Safari iOS Full support 9Samsung Internet Android Full support Yesnodejs Full support 4.0.0
addChrome Full support 38Edge Full support 12Firefox Full support 13IE Partial support 11
Notes
Partial support 11
Notes
Notes Returns 'undefined' instead of the 'Set' object.
Opera Full support 25Safari Full support 8WebView Android Full support 38Chrome Android Full support 38Edge Mobile Full support 12Firefox Android Full support 14Opera Android Full support 25Safari iOS Full support 8Samsung Internet Android Full support Yesnodejs Full support Yes
clearChrome Full support 38Edge Full support 12Firefox Full support 19IE Full support 11Opera Full support 25Safari Full support 8WebView Android Full support 38Chrome Android Full support 38Edge Mobile Full support 12Firefox Android Full support 19Opera Android Full support 25Safari iOS Full support 8Samsung Internet Android Full support Yesnodejs Full support 0.12
deleteChrome Full support 38Edge Full support 12Firefox Full support 13IE Full support 11Opera Full support 25Safari Full support 8WebView Android Full support 38Chrome Android Full support 38Edge Mobile Full support 12Firefox Android Full support 14Opera Android Full support 25Safari iOS Full support 8Samsung Internet Android Full support Yesnodejs Full support 0.12
Full support 0.12
Full support 0.10
Disabled
Disabled From version 0.10: this feature is behind the --harmony runtime flag.
entriesChrome Full support 38Edge Full support 12Firefox Full support 24IE No support NoOpera Full support 25Safari Full support 8WebView Android Full support 38Chrome Android Full support 38Edge Mobile Full support 12Firefox Android Full support 24Opera Android Full support 25Safari iOS Full support 8Samsung Internet Android Full support Yesnodejs Full support 0.12
forEachChrome Full support 38Edge Full support 12Firefox Full support 25IE Full support 11Opera Full support 25Safari Full support 8WebView Android Full support 38Chrome Android Full support 38Edge Mobile Full support 12Firefox Android Full support 25Opera Android Full support 25Safari iOS Full support 8Samsung Internet Android Full support Yesnodejs Full support 0.12
hasChrome Full support 38Edge Full support 12Firefox Full support 13IE Full support 11Opera Full support 25Safari Full support 8WebView Android Full support 38Chrome Android Full support 38Edge Mobile Full support 12Firefox Android Full support 14Opera Android Full support 25Safari iOS Full support 8Samsung Internet Android Full support Yesnodejs Full support Yes
prototypeChrome Full support 38Edge Full support 12Firefox Full support 13IE Full support 11Opera Full support 25Safari Full support 8WebView Android Full support 38Chrome Android Full support 38Edge Mobile Full support 12Firefox Android Full support 14Opera Android Full support 25Safari iOS Full support 8Samsung Internet Android Full support Yesnodejs Full support Yes
sizeChrome Full support 38Edge Full support 12Firefox Full support 19
Notes
Full support 19
Notes
Notes From Firefox 13 to Firefox 18, the size property was implemented as a Set.prototype.size() method, this has been changed to a property in later versions conform to the ECMAScript 2015 specification.
IE Full support 11Opera Full support 25Safari Full support 8WebView Android Full support 38Chrome Android Full support 38Edge Mobile Full support 12Firefox Android Full support 19
Notes
Full support 19
Notes
Notes From Firefox 13 to Firefox 18, the size property was implemented as a Set.prototype.size() method, this has been changed to a property in later versions conform to the ECMAScript 2015 specification.
Opera Android Full support 25Safari iOS Full support 8Samsung Internet Android Full support Yesnodejs Full support 0.12
valuesChrome Full support 38Edge Full support 12Firefox Full support 24IE No support NoOpera Full support 25Safari Full support 8WebView Android Full support 38Chrome Android Full support 38Edge Mobile Full support 12Firefox Android Full support 24Opera Android Full support 25Safari iOS Full support 8Samsung Internet Android Full support Yesnodejs Full support 0.12
@@iteratorChrome Full support YesEdge Full support YesFirefox Full support 36
Full support 36
No support 27 — 36
Notes Alternate Name
Notes A placeholder property named @@iterator is used.
Alternate Name Uses the non-standard name: @@iterator
No support 17 — 27
Notes Alternate Name
Notes A placeholder property named iterator is used.
Alternate Name Uses the non-standard name: iterator
IE No support NoOpera Full support YesSafari Full support YesWebView Android Full support YesChrome Android Full support YesEdge Mobile Full support YesFirefox Android Full support 36
Full support 36
No support 27 — 36
Notes Alternate Name
Notes A placeholder property named @@iterator is used.
Alternate Name Uses the non-standard name: @@iterator
No support 17 — 27
Notes Alternate Name
Notes A placeholder property named iterator is used.
Alternate Name Uses the non-standard name: iterator
Opera Android Full support YesSafari iOS Full support YesSamsung Internet Android Full support Yesnodejs Full support 0.12
@@speciesChrome Full support 51Edge Full support 13Firefox Full support 41IE No support NoOpera Full support 38Safari Full support 10WebView Android Full support 51Chrome Android Full support 51Edge Mobile Full support 13Firefox Android Full support 41Opera Android Full support 41Safari iOS Full support 10Samsung Internet Android Full support 5.0nodejs Full support 6.5.0
Full support 6.5.0
Full support 6.0.0
Disabled
Disabled From version 6.0.0: this feature is behind the --harmony runtime flag.

Legend

Full support  
Full support
Partial support  
Partial support
No support  
No support
See implementation notes.
See implementation notes.
User must explicitly enable this feature.
User must explicitly enable this feature.
Uses a non-standard name.
Uses a non-standard name.

Veja também

Etiquetas do documento e colaboradores

Última atualização por: mdnwebdocs-bot,