Skip to content

Instantly share code, notes, and snippets.

@nitsas
Forked from brettz9/set.js
Last active March 24, 2022 02:18
Show Gist options
  • Save nitsas/8acc439168ad610b7286abf34c1242d3 to your computer and use it in GitHub Desktop.
Save nitsas/8acc439168ad610b7286abf34c1242d3 to your computer and use it in GitHub Desktop.
Simple JS equivalent of the Python set() constructor (without the methods)
/**
* Simple JS equivalent of the Python set() constructor (without the methods)
* @requires shim: Array.prototype.indexOf
* @param {array} arr The array to turn into a set
* @example
* var mySet = set(['red', 'yellow', 'black', 'yellow']);
* mySet.length; // 3
* JSON.stringify(mySet); // ["red","yellow","black"]
* @see For a fuller version, see {@link https://npmjs.org/package/set}
*/
function set (arr) {
return Object.keys(arr.reduce(function (seen, val) {
seen[val] = true;
return seen;
}, {}));
}
@roelzkie15
Copy link

Thanks bro it is very helpful

@konsumer
Copy link

Here's some jsperf to look at. I think filter is faster.

@jairoFernandez
Copy link

thx man

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment