Convert all Values in a Set to Lowercase in JavaScript

avatar

Borislav Hadzhiev

Wed Nov 24 20212 min read

Convert all Values in a Set to Lowercase #

To convert all values in a Set to lowercase, create a second Set, that will store the lowercase values. Use the forEach() method to iterate over the first Set and on each iteration, covert the value to lowercase and add it to the second Set.

index.js
const set1 = new Set(['A', 'B', 'C']); const set2 = new Set(); set1.forEach(value => { set2.add(value.toLowerCase()); }); console.log(set2); // ๐Ÿ‘‰๏ธ {'a', 'b', 'c'}

We created a second Set that will store the lowercase values.

The function we passed to the Set.forEach method gets called with each element in the Set.

On each iteration, we convert the value to lowercase and add it to the new Set.

The Set.add method takes a value as a parameter and adds it to the Set object.

After the last iteration, the second Set contains the lowercase equivalent of the values in the first Set.

An alternative, but also very common approach is to use the Array.map method.

To convert all values in a Set to lowercase:

  1. Convert the Set to an array and call the map() method on the array.
  2. On each iteration, convert the value to lowercase.
  3. Convert the array back to a Set.
index.js
const set1 = new Set(['A', 'B', 'C']); const set2 = new Set( Array.from(set1).map(value => value.toLowerCase()) ); console.log(set2); // ๐Ÿ‘‰๏ธ {'a', 'b', 'c'}

First, we convert the Set to an array, so we can call the map method on it.

The function we passed to the map method gets called with each element in the array.

Whatever we return from the callback function gets added to the array that the map method returns.

On each iteration, we lowercase the array element and return the result.

The last step is to convert the array back to a Set object.

For Set objects that have hundreds of thousands of elements, this approach might be slower than the first, because of the back and forth conversions.

It's a matter of personal preference which approach you pick. I prefer the first one, because it's quite easy to read and does not require any conversions.

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