Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return all values from array in lowercase using for loop instead of map

Tags:

var sorted = words.map(function(value) {     return value.toLowerCase(); }).sort(); 

This code returns all values from words array in lowercase and sorts them, but I wanna do the same with a for loop but I can't.

I tried:

for (var i = 0; i < words.length; i++) {   sorted = [];   sorted.push(words[i].toLowerCase()); }; 
like image 538
Olivera Kovacevic Avatar asked Apr 27 '13 15:04

Olivera Kovacevic


People also ask

How do I convert all the values in an array to lowercase?

To convert all array elements to lowercase:Use the map() method to iterate over the array. On each iteration, call the toLowerCase() method to convert the string to lowercase and return the result. The map method will return a new array containing only lowercase strings.

Can you use toUpperCase in an array?

JavaScript does not really support a toUpperCase() function for arrays, as far as I know. You have to create a for or foreach loop to loop through the array and call . toUpperCase() on each element in the array. Save this answer.

How do I convert all strings to lowercase?

To convert a string to lowercase in Python, use the built-in lower() method of a string. To convert a list of strings to lowercase, use a loop. Alternatively, you can also use a list comprehension.

How do you make all strings in an array lowercase in Java?

Java String toLowerCase() method is used and operated over string where we want to convert all letters to lowercase in a string. There are two types of toLowerCase() method as follows: toLowerCase()


2 Answers

You can also now achieve this very simply by using an arrow function and the map() method of the Array:

var words = ['Foo','Bar','Fizz','Buzz'].map(v => v.toLowerCase());  console.log(words);

Note that map() will only work in browsers which support ES2015. In other words, anything except IE8 and lower.

Similarly, arrow functions will not work at all in IE. For a legacy browser safe version you would need to use an anonymous function:

var words = ['Foo','Bar','Fizz','Buzz'].map(function(v) {    return v.toLowerCase();  });  console.log(words);
like image 184
Rory McCrossan Avatar answered Sep 24 '22 15:09

Rory McCrossan


push is overused.

for (var i = 0, L=words.length ; i < L; i++) {   sorted[i]=words[i].toLowerCase(); } 

If you want fast and have a very large array of words, call toLowerCase once-

sorted=words.join('|').toLowerCase().split('|'); 
like image 21
kennebec Avatar answered Sep 20 '22 15:09

kennebec