Using the ES6 spread operator with Set in Internet Explorer
2 min read Published by Lee Reamsnyder PermalinkI just found this bug in IE11 (and presumably other older browsers) at work, and I didn’t see any clear Google results with the fix, so here goes:
Let’s say you learned a sweet trick to make an array have only unique values using Set()
and the spread operator (...
):
const anArrayWithDuplicates = ['a', 'a', 'b', 'a', 'b', 'c']
const uniquesOnly = [...new Set(anArrayWithDuplicates)]
// -> ['a', 'b', 'c']
In a nutshell: a Set
can only have unique values, and the constructor new Set()
accepts an array for the initial values. So: Make a Set
with the array, spread that into a new array, and 🎊 you have an array with the duplicates removed. Neat.
Mostly.
If you’re trying to make this run in Internet Explorer, you’ll need to include a polyfill for Set
before you try it. The core-js
package has one:
require('core-js/es6/set')
// or import 'core-js/es6/set' if you're going that flavor
const anArrayWithDuplicates = ['a', 'a', 'b', 'a', 'b', 'c']
const uniquesOnly = [...new Set(anArrayWithDuplicates)]
// -> ['a', 'b', 'c']
// but it won't work in IE 😢
// will log something like [object Set]
What isn’t 100% clear is that you also need to include the polyfill for Symbol
, because that includes the Symbol.iterator
magic property that lets you use the spread operator on the new-fangled bits like Set
s:
require('core-js/es6/symbol')
require('core-js/es6/set')
// or like import 'core-js/es6/set' if you're going that flavor
const anArrayWithDuplicates = ['a', 'a', 'b', 'a', 'b', 'c']
const uniquesOnly = [...new Set(anArrayWithDuplicates)]
// -> ['a', 'b', 'c']
// works in IE 🎉
Depending on how you are transpiling your code, another possibility is you might need a polyfill for Array.prototype.from
. It depends on how your transpiler ends up supporting the spread operator.
Or use _.uniq
like a normal person. Whatever.
Lots more on Symbols and iterators at Pony Foo. Reading those articles years ago are the only reason I knew how to fix this as soon as I saw it.