Skip to content

Instantly share code, notes, and snippets.

@brettz9
Last active December 10, 2019 23:18
Show Gist options
  • Save brettz9/6137753 to your computer and use it in GitHub Desktop.
Save brettz9/6137753 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 arr.reduce(function (a, val) {
if (a.indexOf(val) === -1) {
a.push(val);
}
return a;
}, []);
}
@nitsas
Copy link

nitsas commented Jun 3, 2017

Came here after googling "python set in javascript".

For other readers like me, note that this isn't equivalent to Python's set() performance-wise. Python's set uses a hashtable to check if values have been encountered before, whereas this uses Array#indexOf.

If we use an object instead of an array in reduce we can get there performance-wise: fork of this gist

@joemarchese
Copy link

Thank you!

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