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
- How to deploy a Deno app using Docker
- How to deploy an Express app using Docker
- How to deploy a Node app using Docker
- Using Puppeteer and Jest for End-to-End Testing
- How to Scrape the Web using Node.js and Puppeteer
- Getting Started with Handlebars.js
- Creating a Twitter bot with Node.js
- Building a Real-Time Note-Taking App with Vue and Firebase
- Getting Started with React
- Getting Started with Vuex: Managing State in Vue
- Setting Up a Local Web Server using Node.js