How to Reverse the Order of a Set in JavaScript

avatar

Borislav Hadzhiev

Thu Nov 04 20212 min read

Reverse a Set in JavaScript #

To reverse a Set in JavaScript:

  1. Use the Array.from() method to convert the Set to an array.
  2. Call the reverse() method on the array.
  3. Pass the result to the Set() constructor.
  4. The new Set will contain the elements in reverse order.
index.js
const set1 = new Set(['a', 'b', 'c']); const reversed = new Set(Array.from(set1).reverse()); console.log(reversed); // ๐Ÿ‘‰๏ธ {'c', 'b', 'a'}

The first step is to convert the Set to an array. In this example, we used the Array.from method.

index.js
const set1 = new Set(['a', 'b', 'c']); const arr = Array.from(set1); console.log(arr); // ๐Ÿ‘‰๏ธ ['a', 'b', 'c']

The next step is to reverse the array using the Array.reverse() method.

index.js
const set1 = new Set(['a', 'b', 'c']); const arr = Array.from(set1); console.log(arr); // ๐Ÿ‘‰๏ธ ['a', 'b', 'c'] const r = arr.reverse(); console.log(r); // ๐Ÿ‘‰๏ธ ['c', 'b', 'a']

The reverse() method reverses the array in place and returns the result.

The last step is to pass the reversed array as a parameter to the Set() constructor.

The Set() constructor takes an iterable object, such as an array, and adds its elements to a new Set.

The final Set contains the elements of the original Set in reverse order.

A small modification you can do is use the spread syntax (...) instead of the Array.from() method to convert the Set to an array.

index.js
const set1 = new Set(['a', 'b', 'c']); const reversed = new Set([...set1].reverse()); console.log(reversed); // ๐Ÿ‘‰๏ธ {'c', 'b', 'a'}

In this example, we used the spread syntax (...) to unpack the values of the Set into an array, so we can reverse the array.

It's a matter of personal preference which approach you pick. The spread syntax (...) doesn't play nice with TypeScript in some rare scenarios, but other than that achieves the same result.

Further Reading #

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee