Skip to site navigation
Go home

Lee Reamsnyder

Using the ES6 spread operator with Set in Internet Explorer

2018 Oct 11 2 min read Published by Lee Reamsnyder Permalink

I 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 Sets:

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.

← Older post The Rock will be president someday → Newer post We’re back and lookin’ good

Menu

  • Home
  • Blog
  • Work
  • Contact
  • Archives
  • Feeds: RSS | JSON

Search

Elsewhere

  • GitHub
  • Instagram
  • Mastodon
  • Twitter
© Copyright 2006–2023, Lee James Reamsnyder
Back to top