How to Reverse the Order of a Set in JavaScript

avatar

Borislav Hadzhiev

Last updated: Nov 4, 2021

banner

Photo from Unsplash

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 #

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.