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

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);

I know this is a later answer but I've found a prettier and simpler way:

yourArray = ['this', 'iS an', 'arrAy'];
console.log(yourArray); // ["this", "iS an", "arrAy"]

yourLowerArray = yourArray.toLocaleString().toLowerCase().split(',');
console.log(yourLowerArray); //["this", "is an", "array"]

Explaining what this does:

.toLocaleString() -> transform the array into a string separated by commas.

.toLowerCase() -> convert that string to lower case.

.split(',') -> convert the string in lower case back to an array.

Hope this helps you!


With arrays, the += operator does not do what you expect - it calls .toString on the array and concatenates them. Instead, you want to use the array push method:

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

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('|');

Tags:

Javascript