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!
- Getting Started with TypeScript
- Git Tutorial: Learn how to use Version Control
- How to deploy a .NET app using Docker
- How to deploy a Deno app using Docker
- How to deploy a MySQL Server using Docker
- How to deploy an Express app using Docker
- Getting Started with Sass
- Getting Started with Moment.js
- Learn how to build a Slack Bot using Node.js
- Creating a Twitter bot with Node.js
- Using Push.js to Display Web Browser Notifications
- Setting Up Stylus CSS Preprocessor