Convert all array values to LowerCase or UpperCase in JavaScript
Today, we’ll explain to you how to convert all array values to LowerCase or UpperCase in JavaScript. We have several ways to achieve this task but in this short article, we will talk about the two different ways.
Ways to convert all array values to LowerCase or UpperCase
1. Using array map() method
Using array map() method, we can iterate over all elements of the array and convert the case of the element as we want.
Let's take an example for better understanding.
Convert the array values to LowerCase
Here, we will use the string method toLowerCase() along with an array `map()` method to convert the all array values into the LowerCase.
let names = ["John", "William", "Elijah", "Michael"];
let convertedNames = names.map(name => name.toLowerCase());
console.log(convertedNames);
// Output: ["john", "william", "elijah", "michael"]
Convert the array values to UpperCase
The same way to convert the array values into UpperCase using the toUpperCase() method.
let names = ["John", "William", "Elijah", "Michael"];
let convertedNames = names.map(name => name.toUpperCase());
console.log(convertedNames);
// Output: ["JOHN", "WILLIAM", "ELIJAH", "MICHAEL"]
2. Using for loop
Let’s do the same task using the `for` loop.
Convert the array values to LowerCase
let names = ["John", "William", "Elijah", "Michael"];
let convertedNames = [];
for (let i = 0; i < names.length; i++) {
convertedNames[i] = names[i].toLowerCase();
}
console.log(convertedNames);
// Output: ["john", "william", "elijah", "michael"]
Convert the array values to UpperCase
let names = ["John", "William", "Elijah", "Michael"];
let convertedNames = [];
for (let i = 0; i < names.length; i++) {
convertedNames[i] = names[i].toUpperCase();
}
console.log(convertedNames);
// Output: ["JOHN", "WILLIAM", "ELIJAH", "MICHAEL"]
You can also use the below simple way if you have a large array of values.
let convertedNames = names.join('$$').toLowerCase().split('$$');
let convertedNames = names.join('$$').toUpperCase().split('$$');
That’s it for today.
Thank you for reading. Happy Coding..!!