Olivera Kovacevic Olivera Kovacevic - 1 month ago 8
Javascript Question

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

Answer

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