Iterate over a Set in Reverse Order in JavaScript

avatar

Borislav Hadzhiev

Fri Nov 26 20212 min read

banner

Photo by Mr Wong

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 #

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