Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to map an array with uppercase function in javascript?

I'm interested if there is any function like array_map or array_walk from php.

Don't need an for that travels all the array. I can do that for myself.

var array = ['dom', 'lun', 'mar', 'mer', 'gio', 'ven', 'sab'];
// i would like something like this if exists - function(array, 'upperCase');
like image 929
user1236048 Avatar asked Mar 30 '12 08:03

user1236048


People also ask

How do you capitalize an array in JavaScript?

To convert all array elements to uppercase:Use the map() method to iterate over the array. On each iteration, call the toUpperCase() method to convert the string to uppercase and return the result. The map method will return a new array with all strings converted to uppercase.

How do I map an array in JavaScript?

The syntax for the map() method is as follows: arr. map(function(element, index, array){ }, this); The callback function() is called on each array element, and the map() method always passes the current element , the index of the current element, and the whole array object to it.

How do you convert all strings to title caps in a string array?

Convert all the elements in each and every word in to lowercase using string. toLowerCase() method. Loop through first elements of all the words using for loop and convert them in to uppercase.

How do you make an array lowercase in whole?

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.


2 Answers

You can use $.map() in order to apply String.toUpperCase() (or String.toLocaleUpperCase(), if appropriate) to your array items:

var upperCasedArray = $.map(array, String.toUpperCase);

Note that $.map() builds a new array. If you want to modify your existing array in-place, you can use $.each() with an anonymous function:

$.each(array, function(index, item) {
    array[index] = item.toUpperCase();
});

Update: As afanasy rightfully points out in the comments below, mapping String.toUpperCase directly will only work in Gecko-based browsers.

To support the other browsers, you can provide your own function:

var upperCasedArray = $.map(array, function(item, index) {
    return item.toUpperCase();
});
like image 105
Frédéric Hamidi Avatar answered Sep 21 '22 18:09

Frédéric Hamidi


Check out JavaScript Array.map for info on the official JavaScript map function. You can play around with the sample there to see how the function works. Try copying this into the example box:

var array = ['dom', 'lun', 'mar', 'mer', 'gio', 'ven', 'sab'];
var uppers = array.map(function(x) { return x.toUpperCase(); });
console.log(uppers);

And it will print:

DOM,LUN,MAR,MER,GIO,VEN,SAB
like image 39
nkron Avatar answered Sep 25 '22 18:09

nkron