Return all values from array in lowercase using for loop instead of map
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());
};
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);
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('|');
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();
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!
toLowerCase()
is function, you should write ()
after it
I’m assuming you’re declaring sorted
as an array. If so use the push
method rather than +=
:
for (var i = 0; i < words.length; i++) {
sorted.push(words[i].toLowerCase());
}
The toLowerCase method is not being called in your code, only referenced. Change your line in the loop to:
sorted += words[i].toLowerCase();
Add () to call the method.
Complete working code:
var words = ["FOO", "BAR"];
var sorted = [];
for (var i = 0; i < words.length; i++) {
sorted.push(words[i].toLowerCase());
};
console.log(sorted);
words.forEach(function (item, index) {
words[index] = item.toLowerCase();
});