How to convert all Array elements to Lowercase in JavaScript
Table of Contents
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.
JAVASCRIPTconst words = ["Hello", "World"];
console.log(words);
BASH[ 'Hello', 'World' ]
Now let's use the map
method to convert all elements in the array to lowercase.
JAVASCRIPTconst words = ["Hello", "World"];
const lowercaseWords = words.map(word => word.toLowerCase());
console.log(lowercaseWords);
BASH[ '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.
JAVASCRIPTconst words = ["Hello", "World"];
const lowercaseWords = [];
words.forEach(word => lowercaseWords.push(word.toLowerCase()));
console.log(lowercaseWords);
BASH[ '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!
- How to Install Node on Windows, macOS and Linux
- Getting Started with Electron
- How to deploy a .NET app using Docker
- How to build a Discord bot using TypeScript
- How to deploy an Express app using Docker
- Getting Started with Sass
- Getting Started with Handlebars.js
- Getting User Location using JavaScript's Geolocation API
- Getting Started with Moment.js
- Using Push.js to Display Web Browser Notifications
- Getting Started with React
- Setting Up a Local Web Server using Node.js