How to convert all Array elements to Lowercase in JavaScript

Updated onbyAlan Morel
How to convert all Array elements to Lowercase in JavaScript

When you have an array of strings, you might want to convert every string in the array to lowercase.

A good use-case for this is when you want to do a case-insensitive search on an array of strings.

In this post, we'll learn the two easiest ways to convert all elements in an array to lowercase in JavaScript.

Using Array Map method

The most straightforward way to convert all elements in an array to lowercase is to iterate over the array and call .toLowerCase() on each element via the map method.

The map method takes a function as its argument.

The function is called for each element in the array, and the return value of the function is added to the new array.

All we need to do is make the function that we pass to map return the lowercase version of the element.

Let's start by creating an array of strings.

const words = ["Hello", "World"];

console.log(words);
[ 'Hello', 'World' ]

Now let's use the map method to convert all elements in the array to lowercase.

const words = ["Hello", "World"];

const lowercaseWords = words.map(word => word.toLowerCase());

console.log(lowercaseWords);
[ 'hello', 'world' ]

Using iteration

The other way to convert the elements to lowercase is to iterate over the array and call .toLowerCase() on each element and add the result to a new array.

We can iterate over the array using forEach, and push the lowercased element to the new array.

const words = ["Hello", "World"];

const lowercaseWords = [];

words.forEach(word => lowercaseWords.push(word.toLowerCase()));

console.log(lowercaseWords);
[ 'hello', 'world' ]

The only real difference between the two approaches is that using iteration means we need to explicitly create a new array to store the lowercased elements.

Conclusion

In this post, we looked at the two simplest ways to convert all elements in a string array to lowercase in JavaScript.

You can either use the map function or use iteration to go through each element and pushing the lowercased element to a new array.

Thanks for reading!

To learn more about web development, founding a start-up, and bootstrapping a SaaS, follow me on X!
Copyright © 2017 - 2024 Sabe.io. All rights reserved. Made with ❤ in NY.