Iterate over a Set in Reverse Order in JavaScript

avatar

Borislav Hadzhiev

Last updated: Nov 26, 2021

banner

Photo from Unsplash

Iterate over a Set in Reverse Order in JavaScript #

To iterate over a Set in reverse order:

  1. Use the Array.from() method to convert the Set to array.
  2. Use the reverse() method to reverse the array.
  3. Call the forEach method to iterate over the reversed array.
index.js
const set1 = new Set(['a', 'b', 'c']); Array.from(set1) .reverse() .forEach(element => { console.log(element); // 👉️ c, b, a });

The first step is to convert the Set object to an array.

Next, we use the Array.reverse method to reverse the array.

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

Then, we can use the Array.forEach method to iterate over the reversed array.

The function we passed to the forEach method gets called with each element of the array.

An alternative approach is to use the spread syntax (...) to convert the Set to an array.

index.js
const set1 = new Set(['a', 'b', 'c']); [...set1].reverse().forEach(element => { console.log(element); // 👉️ c, b, a });

This code snippet achieves the same result, however this time we used the spread syntax (...) to unpack the values of the Set into an array.

In some very rare cases, the spread syntax (...) doesn't play nice when using TypeScript. If you encounter those, opt for Array.from instead.

An alternative to the forEach method is to use the for...of loop to iterate over the reversed array.

index.js
const set1 = new Set(['a', 'b', 'c']); const reversedArr = [...set1].reverse(); for (const element of reversedArr) { console.log(element); // c, b, a }

The for...of loop is used to iterate over iterable objects, such as arrays, strings, Sets, Maps, etc.

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.